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(db_interfaces): move db interfaces in router to domain_models (#9830)

Jagan59628332de70
diff --git a/Cargo.lock b/Cargo.lock
index 183c316a37..a0cef58bdb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4427,6 +4427,7 @@ dependencies = [
"mime",
"reqwest 0.11.27",
"router_env",
+ "rust-grpc-client",
"serde",
"serde_json",
"strum 0.26.3",
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 2df457dde2..5a9e3b6b06 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -22,7 +22,7 @@ pub mod search;
mod sqlx;
mod types;
use api_event::metrics::{ApiEventMetric, ApiEventMetricRow};
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, types::TenantConfig};
use disputes::metrics::{DisputeMetric, DisputeMetricRow};
use enums::AuthInfo;
use hyperswitch_interfaces::secrets_interface::{
@@ -969,10 +969,7 @@ impl AnalyticsProvider {
}
}
- pub async fn from_conf(
- config: &AnalyticsConfig,
- tenant: &dyn storage_impl::config::TenantConfig,
- ) -> Self {
+ pub async fn from_conf(config: &AnalyticsConfig, tenant: &dyn TenantConfig) -> Self {
match config {
AnalyticsConfig::Sqlx { sqlx, .. } => {
Self::Sqlx(SqlxClient::from_conf(sqlx, tenant.get_schema()).await)
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 70109c5972..0cc1cf797e 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -50,7 +50,7 @@ use crate::{
},
errors::{CustomResult, ParsingError, PercentageError, ValidationError},
fp_utils::when,
- impl_enum_str,
+ id_type, impl_enum_str,
};
/// Represents Percentage Value between 0 and 100 both inclusive
@@ -1441,3 +1441,12 @@ impl_enum_str!(
},
}
);
+
+#[allow(missing_docs)]
+pub trait TenantConfig: Send + Sync {
+ fn get_tenant_id(&self) -> &id_type::TenantId;
+ fn get_schema(&self) -> &str;
+ fn get_accounts_schema(&self) -> &str;
+ fn get_redis_key_prefix(&self) -> &str;
+ fn get_clickhouse_database(&self) -> &str;
+}
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index b0799ae4ec..a7d7a20542 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -3,6 +3,7 @@ use std::collections::{HashMap, HashSet};
use common_enums::connector_enums::Connector;
use common_utils::{consts as common_utils_consts, errors::CustomResult, types::Url};
use error_stack::ResultExt;
+pub use hyperswitch_interfaces::unified_connector_service::transformers::UnifiedConnectorServiceError;
use masking::{PeekInterface, Secret};
use router_env::logger;
use tokio::time::{timeout, Duration};
@@ -22,91 +23,6 @@ use crate::{
utils::deserialize_hashset,
};
-/// Unified Connector Service error variants
-#[derive(Debug, Clone, thiserror::Error)]
-pub enum UnifiedConnectorServiceError {
- /// Error occurred while communicating with the gRPC server.
- #[error("Error from gRPC Server : {0}")]
- ConnectionError(String),
-
- /// Failed to encode the request to the unified connector service.
- #[error("Failed to encode unified connector service request")]
- RequestEncodingFailed,
-
- /// Request encoding failed due to a specific reason.
- #[error("Request encoding failed : {0}")]
- RequestEncodingFailedWithReason(String),
-
- /// Failed to deserialize the response from the connector.
- #[error("Failed to deserialize connector response")]
- ResponseDeserializationFailed,
-
- /// The connector name provided is invalid or unrecognized.
- #[error("An invalid connector name was provided")]
- InvalidConnectorName,
-
- /// Connector name is missing
- #[error("Connector name is missing")]
- MissingConnectorName,
-
- /// A required field was missing in the request.
- #[error("Missing required field: {field_name}")]
- MissingRequiredField {
- /// Missing Field
- field_name: &'static str,
- },
-
- /// Multiple required fields were missing in the request.
- #[error("Missing required fields: {field_names:?}")]
- MissingRequiredFields {
- /// Missing Fields
- field_names: Vec<&'static str>,
- },
-
- /// The requested step or feature is not yet implemented.
- #[error("This step has not been implemented for: {0}")]
- NotImplemented(String),
-
- /// Parsing of some value or input failed.
- #[error("Parsing failed")]
- ParsingFailed,
-
- /// Data format provided is invalid
- #[error("Invalid Data format")]
- InvalidDataFormat {
- /// Field Name for which data is invalid
- field_name: &'static str,
- },
-
- /// Failed to obtain authentication type
- #[error("Failed to obtain authentication type")]
- FailedToObtainAuthType,
-
- /// Failed to inject metadata into request headers
- #[error("Failed to inject metadata into request headers: {0}")]
- HeaderInjectionFailed(String),
-
- /// Failed to perform Payment Authorize from gRPC Server
- #[error("Failed to perform Payment Authorize from gRPC Server")]
- PaymentAuthorizeFailure,
-
- /// Failed to perform Payment Get from gRPC Server
- #[error("Failed to perform Payment Get from gRPC Server")]
- PaymentGetFailure,
-
- /// Failed to perform Payment Setup Mandate from gRPC Server
- #[error("Failed to perform Setup Mandate from gRPC Server")]
- PaymentRegisterFailure,
-
- /// Failed to perform Payment Repeat Payment from gRPC Server
- #[error("Failed to perform Repeat Payment from gRPC Server")]
- PaymentRepeatEverythingFailure,
-
- /// Failed to transform incoming webhook from gRPC Server
- #[error("Failed to transform incoming webhook from gRPC Server")]
- WebhookTransformFailure,
-}
-
/// Result type for Dynamic Routing
pub type UnifiedConnectorServiceResult<T> = CustomResult<T, UnifiedConnectorServiceError>;
/// Contains the Unified Connector Service client
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 42c2398582..f0c656c38a 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -14,14 +14,17 @@ use common_utils::{
#[cfg(feature = "v2")]
use diesel_models::business_profile::RevenueRecoveryAlgorithmData;
use diesel_models::business_profile::{
- AuthenticationConnectorDetails, BusinessPaymentLinkConfig, BusinessPayoutLinkConfig,
- CardTestingGuardConfig, ExternalVaultConnectorDetails, ProfileUpdateInternal, WebhookDetails,
+ self as storage_types, AuthenticationConnectorDetails, BusinessPaymentLinkConfig,
+ BusinessPayoutLinkConfig, CardTestingGuardConfig, ExternalVaultConnectorDetails,
+ ProfileUpdateInternal, WebhookDetails,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
+ behaviour::Conversion,
errors::api_error_response,
+ merchant_key_store::MerchantKeyStore,
type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
};
#[cfg(feature = "v1")]
@@ -950,7 +953,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
#[cfg(feature = "v1")]
#[async_trait::async_trait]
-impl super::behaviour::Conversion for Profile {
+impl Conversion for Profile {
type DstType = diesel_models::business_profile::Profile;
type NewDstType = diesel_models::business_profile::ProfileNew;
@@ -2258,7 +2261,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
#[cfg(feature = "v2")]
#[async_trait::async_trait]
-impl super::behaviour::Conversion for Profile {
+impl Conversion for Profile {
type DstType = diesel_models::business_profile::Profile;
type NewDstType = diesel_models::business_profile::ProfileNew;
@@ -2506,3 +2509,61 @@ impl super::behaviour::Conversion for Profile {
})
}
}
+
+#[async_trait::async_trait]
+pub trait ProfileInterface
+where
+ Profile: Conversion<DstType = storage_types::Profile, NewDstType = storage_types::ProfileNew>,
+{
+ type Error;
+ async fn insert_business_profile(
+ &self,
+ key_manager_state: &keymanager::KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ business_profile: Profile,
+ ) -> CustomResult<Profile, Self::Error>;
+
+ async fn find_business_profile_by_profile_id(
+ &self,
+ key_manager_state: &keymanager::KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<Profile, Self::Error>;
+
+ async fn find_business_profile_by_merchant_id_profile_id(
+ &self,
+ key_manager_state: &keymanager::KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<Profile, Self::Error>;
+
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ key_manager_state: &keymanager::KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_name: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Profile, Self::Error>;
+
+ async fn update_profile_by_profile_id(
+ &self,
+ key_manager_state: &keymanager::KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ current_state: Profile,
+ profile_update: ProfileUpdate,
+ ) -> CustomResult<Profile, Self::Error>;
+
+ async fn delete_profile_by_profile_id_merchant_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, Self::Error>;
+
+ async fn list_profile_by_merchant_id(
+ &self,
+ key_manager_state: &keymanager::KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<Profile>, Self::Error>;
+}
diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rs
new file mode 100644
index 0000000000..eadf8e5c81
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/configs.rs
@@ -0,0 +1,39 @@
+use common_utils::errors::CustomResult;
+use diesel_models::configs as storage;
+
+#[async_trait::async_trait]
+pub trait ConfigInterface {
+ type Error;
+ async fn insert_config(
+ &self,
+ 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(
+ &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>;
+
+ async fn find_config_by_key_from_db(
+ &self,
+ key: &str,
+ ) -> CustomResult<storage::Config, Self::Error>;
+
+ async fn update_config_by_key(
+ &self,
+ key: &str,
+ 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/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index 6179e22169..84c9510c4b 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -17,7 +17,8 @@ use diesel_models::{
customers as storage_types, customers::CustomerUpdateInternal, query::customers as query,
};
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret, SwitchStrategy};
+use masking::{ExposeOptionInterface, PeekInterface, Secret, SwitchStrategy};
+use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
use time::PrimitiveDateTime;
@@ -685,3 +686,57 @@ where
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
}
+
+#[cfg(feature = "v1")]
+#[instrument]
+pub async fn update_connector_customer_in_customers(
+ connector_label: &str,
+ customer: Option<&Customer>,
+ connector_customer_id: Option<String>,
+) -> Option<CustomerUpdate> {
+ let mut connector_customer_map = customer
+ .and_then(|customer| customer.connector_customer.clone().expose_option())
+ .and_then(|connector_customer| connector_customer.as_object().cloned())
+ .unwrap_or_default();
+
+ let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| {
+ let connector_customer_value = serde_json::Value::String(connector_customer_id);
+ connector_customer_map.insert(connector_label.to_string(), connector_customer_value);
+ connector_customer_map
+ });
+
+ updated_connector_customer_map
+ .map(serde_json::Value::Object)
+ .map(
+ |connector_customer_value| CustomerUpdate::ConnectorCustomer {
+ connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)),
+ },
+ )
+}
+
+#[cfg(feature = "v2")]
+#[instrument]
+pub async fn update_connector_customer_in_customers(
+ merchant_connector_account: &MerchantConnectorAccountTypeDetails,
+ customer: Option<&Customer>,
+ connector_customer_id: Option<String>,
+) -> Option<CustomerUpdate> {
+ match merchant_connector_account {
+ MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
+ connector_customer_id.map(|new_conn_cust_id| {
+ let connector_account_id = account.get_id().clone();
+ let mut connector_customer_map = customer
+ .and_then(|customer| customer.connector_customer.clone())
+ .unwrap_or_default();
+ connector_customer_map.insert(connector_account_id, new_conn_cust_id);
+ CustomerUpdate::ConnectorCustomer {
+ connector_customer: Some(connector_customer_map),
+ }
+ })
+ }
+ // TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
+ MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
+ todo!("Handle connector_customer construction for MerchantConnectorDetails");
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 1a3da30c97..1fb3976376 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -8,6 +8,7 @@ pub mod callback_mapper;
pub mod card_testing_guard_data;
pub mod cards_info;
pub mod chat;
+pub mod configs;
pub mod connector_endpoints;
pub mod consts;
pub mod customer;
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index 29105e44e2..86b0f9f139 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -14,7 +14,11 @@ use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
-use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
+use crate::{
+ behaviour::Conversion,
+ merchant_key_store,
+ type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
+};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
@@ -586,7 +590,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
#[cfg(feature = "v2")]
#[async_trait::async_trait]
-impl super::behaviour::Conversion for MerchantAccount {
+impl Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
@@ -702,7 +706,7 @@ impl super::behaviour::Conversion for MerchantAccount {
#[cfg(feature = "v1")]
#[async_trait::async_trait]
-impl super::behaviour::Conversion for MerchantAccount {
+impl Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
@@ -878,3 +882,87 @@ impl MerchantAccount {
metadata.and_then(|a| a.compatible_connector)
}
}
+
+#[async_trait::async_trait]
+pub trait MerchantAccountInterface
+where
+ MerchantAccount: Conversion<
+ DstType = diesel_models::merchant_account::MerchantAccount,
+ NewDstType = diesel_models::merchant_account::MerchantAccountNew,
+ >,
+{
+ type Error;
+ async fn insert_merchant(
+ &self,
+ state: &keymanager::KeyManagerState,
+ merchant_account: MerchantAccount,
+ merchant_key_store: &merchant_key_store::MerchantKeyStore,
+ ) -> CustomResult<MerchantAccount, Self::Error>;
+
+ async fn find_merchant_account_by_merchant_id(
+ &self,
+ state: &keymanager::KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &merchant_key_store::MerchantKeyStore,
+ ) -> CustomResult<MerchantAccount, Self::Error>;
+
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account: MerchantAccountUpdate,
+ ) -> CustomResult<usize, Self::Error>;
+
+ async fn update_merchant(
+ &self,
+ state: &keymanager::KeyManagerState,
+ this: MerchantAccount,
+ merchant_account: MerchantAccountUpdate,
+ merchant_key_store: &merchant_key_store::MerchantKeyStore,
+ ) -> CustomResult<MerchantAccount, Self::Error>;
+
+ async fn update_specific_fields_in_merchant(
+ &self,
+ state: &keymanager::KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_account: MerchantAccountUpdate,
+ merchant_key_store: &merchant_key_store::MerchantKeyStore,
+ ) -> CustomResult<MerchantAccount, Self::Error>;
+
+ async fn find_merchant_account_by_publishable_key(
+ &self,
+ state: &keymanager::KeyManagerState,
+ publishable_key: &str,
+ ) -> CustomResult<(MerchantAccount, merchant_key_store::MerchantKeyStore), Self::Error>;
+
+ #[cfg(feature = "olap")]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ state: &keymanager::KeyManagerState,
+ organization_id: &common_utils::id_type::OrganizationId,
+ ) -> CustomResult<Vec<MerchantAccount>, Self::Error>;
+
+ async fn delete_merchant_account_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, Self::Error>;
+
+ #[cfg(feature = "olap")]
+ async fn list_multiple_merchant_accounts(
+ &self,
+ state: &keymanager::KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ ) -> CustomResult<Vec<MerchantAccount>, Self::Error>;
+
+ #[cfg(feature = "olap")]
+ async fn list_merchant_and_org_ids(
+ &self,
+ state: &keymanager::KeyManagerState,
+ limit: u32,
+ offset: Option<u32>,
+ ) -> CustomResult<
+ Vec<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::OrganizationId,
+ )>,
+ Self::Error,
+ >;
+}
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index d6600d674f..99fdea17cf 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -16,7 +16,10 @@ use diesel_models::merchant_connector_account::{
MerchantConnectorAccountFeatureMetadata as DieselMerchantConnectorAccountFeatureMetadata,
RevenueRecoveryMetadata as DieselRevenueRecoveryMetadata,
};
-use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountUpdateInternal};
+use diesel_models::{
+ enums,
+ merchant_connector_account::{self as storage, MerchantConnectorAccountUpdateInternal},
+};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
@@ -27,6 +30,7 @@ use super::behaviour;
use crate::errors::api_error_response;
use crate::{
mandates::CommonMandateReference,
+ merchant_key_store::MerchantKeyStore,
router_data,
type_encryption::{crypto_operation, CryptoOperation},
};
@@ -492,40 +496,38 @@ pub enum MerchantConnectorAccountUpdate {
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for MerchantConnectorAccount {
- type DstType = diesel_models::merchant_connector_account::MerchantConnectorAccount;
- type NewDstType = diesel_models::merchant_connector_account::MerchantConnectorAccountNew;
+ type DstType = storage::MerchantConnectorAccount;
+ type NewDstType = storage::MerchantConnectorAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
- Ok(
- diesel_models::merchant_connector_account::MerchantConnectorAccount {
- merchant_id: self.merchant_id,
- connector_name: self.connector_name,
- connector_account_details: self.connector_account_details.into(),
- test_mode: self.test_mode,
- disabled: self.disabled,
- merchant_connector_id: self.merchant_connector_id.clone(),
- id: Some(self.merchant_connector_id),
- payment_methods_enabled: self.payment_methods_enabled,
- connector_type: self.connector_type,
- metadata: self.metadata,
- frm_configs: None,
- frm_config: self.frm_configs,
- business_country: self.business_country,
- business_label: self.business_label,
- connector_label: self.connector_label,
- business_sub_label: self.business_sub_label,
- created_at: self.created_at,
- modified_at: self.modified_at,
- connector_webhook_details: self.connector_webhook_details,
- profile_id: Some(self.profile_id),
- applepay_verified_domains: self.applepay_verified_domains,
- pm_auth_config: self.pm_auth_config,
- status: self.status,
- connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
- additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
- version: self.version,
- },
- )
+ Ok(storage::MerchantConnectorAccount {
+ merchant_id: self.merchant_id,
+ connector_name: self.connector_name,
+ connector_account_details: self.connector_account_details.into(),
+ test_mode: self.test_mode,
+ disabled: self.disabled,
+ merchant_connector_id: self.merchant_connector_id.clone(),
+ id: Some(self.merchant_connector_id),
+ payment_methods_enabled: self.payment_methods_enabled,
+ connector_type: self.connector_type,
+ metadata: self.metadata,
+ frm_configs: None,
+ frm_config: self.frm_configs,
+ business_country: self.business_country,
+ business_label: self.business_label,
+ connector_label: self.connector_label,
+ business_sub_label: self.business_sub_label,
+ created_at: self.created_at,
+ modified_at: self.modified_at,
+ connector_webhook_details: self.connector_webhook_details,
+ profile_id: Some(self.profile_id),
+ applepay_verified_domains: self.applepay_verified_domains,
+ pm_auth_config: self.pm_auth_config,
+ status: self.status,
+ connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
+ version: self.version,
+ })
}
async fn convert_back(
@@ -628,35 +630,33 @@ impl behaviour::Conversion for MerchantConnectorAccount {
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for MerchantConnectorAccount {
- type DstType = diesel_models::merchant_connector_account::MerchantConnectorAccount;
- type NewDstType = diesel_models::merchant_connector_account::MerchantConnectorAccountNew;
+ type DstType = storage::MerchantConnectorAccount;
+ type NewDstType = storage::MerchantConnectorAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
- Ok(
- diesel_models::merchant_connector_account::MerchantConnectorAccount {
- id: self.id,
- merchant_id: self.merchant_id,
- connector_name: self.connector_name,
- connector_account_details: self.connector_account_details.into(),
- disabled: self.disabled,
- payment_methods_enabled: self.payment_methods_enabled,
- connector_type: self.connector_type,
- metadata: self.metadata,
- frm_config: self.frm_configs,
- connector_label: self.connector_label,
- created_at: self.created_at,
- modified_at: self.modified_at,
- connector_webhook_details: self.connector_webhook_details,
- profile_id: self.profile_id,
- applepay_verified_domains: self.applepay_verified_domains,
- pm_auth_config: self.pm_auth_config,
- status: self.status,
- connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
- additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
- version: self.version,
- feature_metadata: self.feature_metadata.map(From::from),
- },
- )
+ Ok(storage::MerchantConnectorAccount {
+ id: self.id,
+ merchant_id: self.merchant_id,
+ connector_name: self.connector_name,
+ connector_account_details: self.connector_account_details.into(),
+ disabled: self.disabled,
+ payment_methods_enabled: self.payment_methods_enabled,
+ connector_type: self.connector_type,
+ metadata: self.metadata,
+ frm_config: self.frm_configs,
+ connector_label: self.connector_label,
+ created_at: self.created_at,
+ modified_at: self.modified_at,
+ connector_webhook_details: self.connector_webhook_details,
+ profile_id: self.profile_id,
+ applepay_verified_domains: self.applepay_verified_domains,
+ pm_auth_config: self.pm_auth_config,
+ status: self.status,
+ connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
+ version: self.version,
+ feature_metadata: self.feature_metadata.map(From::from),
+ })
}
async fn convert_back(
@@ -998,3 +998,117 @@ impl From<DieselMerchantConnectorAccountFeatureMetadata>
Self { revenue_recovery }
}
}
+
+#[async_trait::async_trait]
+pub trait MerchantConnectorAccountInterface
+where
+ MerchantConnectorAccount: behaviour::Conversion<
+ DstType = storage::MerchantConnectorAccount,
+ NewDstType = storage::MerchantConnectorAccountNew,
+ >,
+{
+ type Error;
+ #[cfg(feature = "v1")]
+ async fn find_merchant_connector_account_by_merchant_id_connector_label(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &id_type::MerchantId,
+ connector_label: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccount, Self::Error>;
+
+ #[cfg(feature = "v1")]
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &id_type::ProfileId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccount, Self::Error>;
+
+ #[cfg(feature = "v1")]
+ async fn find_merchant_connector_account_by_merchant_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &id_type::MerchantId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>;
+
+ async fn insert_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ t: MerchantConnectorAccount,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccount, Self::Error>;
+
+ #[cfg(feature = "v1")]
+ async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &id_type::MerchantId,
+ merchant_connector_id: &id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccount, Self::Error>;
+
+ #[cfg(feature = "v2")]
+ async fn find_merchant_connector_account_by_id(
+ &self,
+ state: &KeyManagerState,
+ id: &id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccount, Self::Error>;
+
+ async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &id_type::MerchantId,
+ get_disabled: bool,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccounts, Self::Error>;
+
+ #[cfg(all(feature = "olap", feature = "v2"))]
+ async fn list_connector_account_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>;
+
+ async fn list_enabled_connector_accounts_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ connector_type: common_enums::ConnectorType,
+ ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>;
+
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: MerchantConnectorAccount,
+ merchant_connector_account: MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<MerchantConnectorAccount, Self::Error>;
+
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ this: Vec<(
+ MerchantConnectorAccount,
+ MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), Self::Error>;
+
+ #[cfg(feature = "v1")]
+ async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ merchant_connector_id: &id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, Self::Error>;
+
+ #[cfg(feature = "v2")]
+ async fn delete_merchant_connector_account_by_id(
+ &self,
+ id: &id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, Self::Error>;
+}
diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
index d24e23c579..ebef0b4706 100644
--- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
@@ -68,3 +68,42 @@ impl super::behaviour::Conversion for MerchantKeyStore {
})
}
}
+
+#[async_trait::async_trait]
+pub trait MerchantKeyStoreInterface {
+ type Error;
+ async fn insert_merchant_key_store(
+ &self,
+ state: &KeyManagerState,
+ merchant_key_store: MerchantKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<MerchantKeyStore, Self::Error>;
+
+ async fn get_merchant_key_store_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<MerchantKeyStore, Self::Error>;
+
+ async fn delete_merchant_key_store_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, Self::Error>;
+
+ #[cfg(feature = "olap")]
+ async fn list_multiple_key_stores(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>;
+
+ async fn get_all_key_stores(
+ &self,
+ state: &KeyManagerState,
+ key: &Secret<Vec<u8>>,
+ from: u32,
+ to: u32,
+ ) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>;
+}
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
index 6b216d5c86..199715a146 100644
--- a/crates/hyperswitch_interfaces/Cargo.toml
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -29,6 +29,7 @@ serde_json = "1.0.140"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.69"
time = "0.3.41"
+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "f719688943adf7bc17bb93dcb43f27485c17a96e", package = "rust-grpc-client" }
# First party crates
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
diff --git a/crates/hyperswitch_interfaces/src/api_client.rs b/crates/hyperswitch_interfaces/src/api_client.rs
new file mode 100644
index 0000000000..32c007c2ca
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/api_client.rs
@@ -0,0 +1,658 @@
+use std::{
+ fmt::Debug,
+ time::{Duration, Instant},
+};
+
+use common_enums::ApiClientError;
+use common_utils::{
+ consts::{X_CONNECTOR_NAME, X_FLOW_NAME, X_REQUEST_ID},
+ errors::CustomResult,
+ request::{Request, RequestContent},
+};
+use error_stack::{report, ResultExt};
+use http::Method;
+use hyperswitch_domain_models::{
+ errors::api_error_response,
+ router_data::{ErrorResponse, RouterData},
+};
+use masking::Maskable;
+use reqwest::multipart::Form;
+use router_env::{instrument, logger, tracing, tracing_actix_web::RequestId};
+use serde_json::json;
+
+use crate::{
+ configs,
+ connector_integration_interface::{
+ BoxedConnectorIntegrationInterface, ConnectorEnum, RouterDataConversion,
+ },
+ consts,
+ errors::ConnectorError,
+ events,
+ events::connector_api_logs::ConnectorEvent,
+ metrics, types,
+ types::Proxy,
+ unified_connector_service,
+};
+
+/// A trait representing a converter for connector names to their corresponding enum variants.
+pub trait ConnectorConverter: Send + Sync {
+ /// Get the connector enum variant by its name
+ fn get_connector_enum_by_name(
+ &self,
+ connector: &str,
+ ) -> CustomResult<ConnectorEnum, api_error_response::ApiErrorResponse>;
+}
+/// A trait representing a builder for HTTP requests.
+pub trait RequestBuilder: Send + Sync {
+ /// Build a JSON request
+ fn json(&mut self, body: serde_json::Value);
+ /// Build a URL encoded form request
+ fn url_encoded_form(&mut self, body: serde_json::Value);
+ /// Set the timeout duration for the request
+ fn timeout(&mut self, timeout: Duration);
+ /// Build a multipart request
+ fn multipart(&mut self, form: Form);
+ /// Add a header to the request
+ fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError>;
+ /// Send the request and return a future that resolves to the response
+ fn send(
+ self,
+ ) -> CustomResult<
+ Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>,
+ ApiClientError,
+ >;
+}
+
+/// A trait representing an API client capable of making HTTP requests.
+#[async_trait::async_trait]
+pub trait ApiClient: dyn_clone::DynClone
+where
+ Self: Send + Sync,
+{
+ /// Create a new request with the specified HTTP method and URL
+ fn request(
+ &self,
+ method: Method,
+ url: String,
+ ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
+
+ /// Create a new request with the specified HTTP method, URL, and client certificate
+ fn request_with_certificate(
+ &self,
+ method: Method,
+ url: String,
+ certificate: Option<masking::Secret<String>>,
+ certificate_key: Option<masking::Secret<String>>,
+ ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
+
+ /// Send a request and return the response
+ async fn send_request(
+ &self,
+ state: &dyn ApiClientWrapper,
+ request: Request,
+ option_timeout_secs: Option<u64>,
+ forward_to_kafka: bool,
+ ) -> CustomResult<reqwest::Response, ApiClientError>;
+
+ /// Add a request ID to the client for tracking purposes
+ fn add_request_id(&mut self, request_id: RequestId);
+
+ /// Get the current request ID, if any
+ fn get_request_id(&self) -> Option<RequestId>;
+
+ /// Get the current request ID as a string, if any
+ fn get_request_id_str(&self) -> Option<String>;
+
+ /// Add a flow name to the client for tracking purposes
+ fn add_flow_name(&mut self, flow_name: String);
+}
+
+dyn_clone::clone_trait_object!(ApiClient);
+
+/// A wrapper trait to get the ApiClient and Proxy from the state
+pub trait ApiClientWrapper: Send + Sync {
+ /// Get the ApiClient instance
+ fn get_api_client(&self) -> &dyn ApiClient;
+ /// Get the Proxy configuration
+ fn get_proxy(&self) -> Proxy;
+ /// Get the request ID as String if any
+ fn get_request_id_str(&self) -> Option<String>;
+ /// Get the request ID as &RequestId if any
+ fn get_request_id(&self) -> Option<RequestId>;
+ /// Get the tenant information
+ fn get_tenant(&self) -> configs::Tenant;
+ /// Get connectors configuration
+ fn get_connectors(&self) -> configs::Connectors;
+ /// Get the event handler
+ fn event_handler(&self) -> &dyn events::EventHandlerInterface;
+}
+
+/// Handle the flow by interacting with connector module
+/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
+/// In other cases, It will be created if required, even if it is not passed
+#[instrument(skip_all, fields(connector_name, payment_method))]
+pub async fn execute_connector_processing_step<
+ 'b,
+ 'a,
+ T,
+ ResourceCommonData: Clone + RouterDataConversion<T, Req, Resp> + 'static,
+ Req: Debug + Clone + 'static,
+ Resp: Debug + Clone + 'static,
+>(
+ state: &dyn ApiClientWrapper,
+ connector_integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>,
+ req: &'b RouterData<T, Req, Resp>,
+ call_connector_action: common_enums::CallConnectorAction,
+ connector_request: Option<Request>,
+ return_raw_connector_response: Option<bool>,
+) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
+where
+ T: Clone + Debug + 'static,
+ // BoxedConnectorIntegration<T, Req, Resp>: 'b,
+{
+ // If needed add an error stack as follows
+ // connector_integration.build_request(req).attach_printable("Failed to build request");
+ tracing::Span::current().record("connector_name", &req.connector);
+ tracing::Span::current().record("payment_method", req.payment_method.to_string());
+ logger::debug!(connector_request=?connector_request);
+ let mut router_data = req.clone();
+ match call_connector_action {
+ common_enums::CallConnectorAction::HandleResponse(res) => {
+ let response = types::Response {
+ headers: None,
+ response: res.into(),
+ status_code: 200,
+ };
+ connector_integration.handle_response(req, None, response)
+ }
+ common_enums::CallConnectorAction::UCSHandleResponse(transform_data_bytes) => {
+ handle_ucs_response(router_data, transform_data_bytes)
+ }
+ common_enums::CallConnectorAction::Avoid => Ok(router_data),
+ common_enums::CallConnectorAction::StatusUpdate {
+ status,
+ error_code,
+ error_message,
+ } => {
+ router_data.status = status;
+ let error_response = if error_code.is_some() | error_message.is_some() {
+ Some(ErrorResponse {
+ code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ status_code: 200, // This status code is ignored in redirection response it will override with 302 status code.
+ reason: None,
+ attempt_status: None,
+ connector_transaction_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ None
+ };
+ router_data.response = error_response.map(Err).unwrap_or(router_data.response);
+ Ok(router_data)
+ }
+ common_enums::CallConnectorAction::Trigger => {
+ metrics::CONNECTOR_CALL_COUNT.add(
+ 1,
+ router_env::metric_attributes!(
+ ("connector", req.connector.to_string()),
+ (
+ "flow",
+ get_flow_name::<T>().unwrap_or_else(|_| "UnknownFlow".to_string())
+ ),
+ ),
+ );
+
+ let connector_request = match connector_request {
+ Some(connector_request) => Some(connector_request),
+ None => connector_integration
+ .build_request(req, &state.get_connectors())
+ .inspect_err(|error| {
+ if matches!(
+ error.current_context(),
+ &ConnectorError::RequestEncodingFailed
+ | &ConnectorError::RequestEncodingFailedWithReason(_)
+ ) {
+ metrics::REQUEST_BUILD_FAILURE.add(
+ 1,
+ router_env::metric_attributes!((
+ "connector",
+ req.connector.clone()
+ )),
+ )
+ }
+ })?,
+ };
+
+ match connector_request {
+ Some(mut request) => {
+ let masked_request_body = match &request.body {
+ Some(request) => match request {
+ RequestContent::Json(i)
+ | RequestContent::FormUrlEncoded(i)
+ | RequestContent::Xml(i) => i
+ .masked_serialize()
+ .unwrap_or(json!({ "error": "failed to mask serialize"})),
+ RequestContent::FormData((_, i)) => i
+ .masked_serialize()
+ .unwrap_or(json!({ "error": "failed to mask serialize"})),
+ RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}),
+ },
+ None => serde_json::Value::Null,
+ };
+ let flow_name =
+ get_flow_name::<T>().unwrap_or_else(|_| "UnknownFlow".to_string());
+ request.headers.insert((
+ X_FLOW_NAME.to_string(),
+ Maskable::Masked(masking::Secret::new(flow_name.to_string())),
+ ));
+ let connector_name = req.connector.clone();
+ request.headers.insert((
+ X_CONNECTOR_NAME.to_string(),
+ Maskable::Masked(masking::Secret::new(connector_name.clone().to_string())),
+ ));
+ state.get_request_id().as_ref().map(|id| {
+ let request_id = id.to_string();
+ request.headers.insert((
+ X_REQUEST_ID.to_string(),
+ Maskable::Normal(request_id.clone()),
+ ));
+ request_id
+ });
+ let request_url = request.url.clone();
+ let request_method = request.method;
+ let current_time = Instant::now();
+ let response =
+ call_connector_api(state, request, "execute_connector_processing_step")
+ .await;
+ let external_latency = current_time.elapsed().as_millis();
+ logger::info!(raw_connector_request=?masked_request_body);
+ let status_code = response
+ .as_ref()
+ .map(|i| {
+ i.as_ref()
+ .map_or_else(|value| value.status_code, |value| value.status_code)
+ })
+ .unwrap_or_default();
+ let mut connector_event = ConnectorEvent::new(
+ state.get_tenant().tenant_id.clone(),
+ req.connector.clone(),
+ std::any::type_name::<T>(),
+ masked_request_body,
+ request_url,
+ request_method,
+ req.payment_id.clone(),
+ req.merchant_id.clone(),
+ state.get_request_id().as_ref(),
+ external_latency,
+ req.refund_id.clone(),
+ req.dispute_id.clone(),
+ status_code,
+ );
+
+ match response {
+ Ok(body) => {
+ let response = match body {
+ Ok(body) => {
+ let connector_http_status_code = Some(body.status_code);
+ let handle_response_result = connector_integration
+ .handle_response(
+ req,
+ Some(&mut connector_event),
+ body.clone(),
+ )
+ .inspect_err(|error| {
+ if error.current_context()
+ == &ConnectorError::ResponseDeserializationFailed
+ {
+ metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
+ 1,
+ router_env::metric_attributes!((
+ "connector",
+ req.connector.clone(),
+ )),
+ )
+ }
+ });
+ match handle_response_result {
+ Ok(mut data) => {
+ state
+ .event_handler()
+ .log_connector_event(&connector_event);
+ data.connector_http_status_code =
+ connector_http_status_code;
+ // Add up multiple external latencies in case of multiple external calls within the same request.
+ data.external_latency = Some(
+ data.external_latency
+ .map_or(external_latency, |val| {
+ val + external_latency
+ }),
+ );
+
+ store_raw_connector_response_if_required(
+ return_raw_connector_response,
+ &mut data,
+ &body,
+ )?;
+
+ Ok(data)
+ }
+ Err(err) => {
+ connector_event
+ .set_error(json!({"error": err.to_string()}));
+
+ state
+ .event_handler()
+ .log_connector_event(&connector_event);
+ Err(err)
+ }
+ }?
+ }
+ Err(body) => {
+ router_data.connector_http_status_code = Some(body.status_code);
+ router_data.external_latency = Some(
+ router_data
+ .external_latency
+ .map_or(external_latency, |val| val + external_latency),
+ );
+ metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
+ 1,
+ router_env::metric_attributes!((
+ "connector",
+ req.connector.clone(),
+ )),
+ );
+
+ store_raw_connector_response_if_required(
+ return_raw_connector_response,
+ &mut router_data,
+ &body,
+ )?;
+
+ let error = match body.status_code {
+ 500..=511 => {
+ let error_res = connector_integration
+ .get_5xx_error_response(
+ body,
+ Some(&mut connector_event),
+ )?;
+ state
+ .event_handler()
+ .log_connector_event(&connector_event);
+ error_res
+ }
+ _ => {
+ let error_res = connector_integration
+ .get_error_response(
+ body,
+ Some(&mut connector_event),
+ )?;
+ if let Some(status) = error_res.attempt_status {
+ router_data.status = status;
+ };
+ state
+ .event_handler()
+ .log_connector_event(&connector_event);
+ error_res
+ }
+ };
+
+ router_data.response = Err(error);
+
+ router_data
+ }
+ };
+ Ok(response)
+ }
+ Err(error) => {
+ connector_event.set_error(json!({"error": error.to_string()}));
+ state.event_handler().log_connector_event(&connector_event);
+ if error.current_context().is_upstream_timeout() {
+ let error_response = ErrorResponse {
+ code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
+ message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
+ reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
+ status_code: 504,
+ attempt_status: None,
+ connector_transaction_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ };
+ router_data.response = Err(error_response);
+ router_data.connector_http_status_code = Some(504);
+ router_data.external_latency = Some(
+ router_data
+ .external_latency
+ .map_or(external_latency, |val| val + external_latency),
+ );
+ Ok(router_data)
+ } else {
+ Err(error
+ .change_context(ConnectorError::ProcessingStepFailed(None)))
+ }
+ }
+ }
+ }
+ None => Ok(router_data),
+ }
+ }
+ }
+}
+
+/// Handle UCS webhook response processing
+pub fn handle_ucs_response<T, Req, Resp>(
+ router_data: RouterData<T, Req, Resp>,
+ transform_data_bytes: Vec<u8>,
+) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
+where
+ T: Clone + Debug + 'static,
+ Req: Debug + Clone + 'static,
+ Resp: Debug + Clone + 'static,
+{
+ let webhook_transform_data: unified_connector_service::WebhookTransformData =
+ serde_json::from_slice(&transform_data_bytes)
+ .change_context(ConnectorError::ResponseDeserializationFailed)
+ .attach_printable("Failed to deserialize UCS webhook transform data")?;
+
+ let webhook_content = webhook_transform_data
+ .webhook_content
+ .ok_or(ConnectorError::ResponseDeserializationFailed)
+ .attach_printable("UCS webhook transform data missing webhook_content")?;
+
+ let payment_get_response = match webhook_content.content {
+ Some(unified_connector_service_client::payments::webhook_response_content::Content::PaymentsResponse(payments_response)) => {
+ Ok(payments_response)
+ },
+ Some(unified_connector_service_client::payments::webhook_response_content::Content::RefundsResponse(_)) => {
+ Err(ConnectorError::ProcessingStepFailed(Some("UCS webhook contains refund response but payment processing was expected".to_string().into())).into())
+ },
+ Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => {
+ Err(ConnectorError::ProcessingStepFailed(Some("UCS webhook contains dispute response but payment processing was expected".to_string().into())).into())
+ },
+ Some(unified_connector_service_client::payments::webhook_response_content::Content::IncompleteTransformation(_)) => {
+ Err(ConnectorError::ProcessingStepFailed(Some("UCS webhook contains incomplete transformation but payment processing was expected".to_string().into())).into())
+ },
+ None => {
+ Err(ConnectorError::ResponseDeserializationFailed)
+ .attach_printable("UCS webhook content missing payments_response")
+ }
+ }?;
+
+ let (router_data_response, status_code) =
+ unified_connector_service::handle_unified_connector_service_response_for_payment_get(
+ payment_get_response.clone(),
+ )
+ .change_context(ConnectorError::ProcessingStepFailed(None))
+ .attach_printable("Failed to process UCS webhook response using PSync handler")?;
+
+ let mut updated_router_data = router_data;
+ let router_data_response = router_data_response.map(|(response, status)| {
+ updated_router_data.status = status;
+ response
+ });
+
+ let _ = router_data_response.map_err(|error_response| {
+ updated_router_data.response = Err(error_response);
+ });
+ updated_router_data.raw_connector_response = payment_get_response
+ .raw_connector_response
+ .map(masking::Secret::new);
+ updated_router_data.connector_http_status_code = Some(status_code);
+
+ Ok(updated_router_data)
+}
+
+/// Calls the connector API and handles the response
+#[instrument(skip_all)]
+pub async fn call_connector_api(
+ state: &dyn ApiClientWrapper,
+ request: Request,
+ flow_name: &str,
+) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> {
+ let current_time = Instant::now();
+ let headers = request.headers.clone();
+ let url = request.url.clone();
+ let response = state
+ .get_api_client()
+ .send_request(state, request, None, true)
+ .await;
+
+ match response.as_ref() {
+ Ok(resp) => {
+ let status_code = resp.status().as_u16();
+ let elapsed_time = current_time.elapsed();
+ logger::info!(
+ ?headers,
+ url,
+ status_code,
+ flow=?flow_name,
+ ?elapsed_time
+ );
+ }
+ Err(err) => {
+ logger::info!(
+ call_connector_api_error=?err
+ );
+ }
+ }
+
+ handle_response(response).await
+}
+
+/// Handle the response from the API call
+#[instrument(skip_all)]
+pub async fn handle_response(
+ response: CustomResult<reqwest::Response, ApiClientError>,
+) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> {
+ response
+ .map(|response| async {
+ logger::info!(?response);
+ let status_code = response.status().as_u16();
+ let headers = Some(response.headers().to_owned());
+ match status_code {
+ 200..=202 | 302 | 204 => {
+ // If needed add log line
+ // logger:: error!( error_parsing_response=?err);
+ let response = response
+ .bytes()
+ .await
+ .change_context(ApiClientError::ResponseDecodingFailed)
+ .attach_printable("Error while waiting for response")?;
+ Ok(Ok(types::Response {
+ headers,
+ response,
+ status_code,
+ }))
+ }
+
+ status_code @ 500..=599 => {
+ let bytes = response.bytes().await.map_err(|error| {
+ report!(error)
+ .change_context(ApiClientError::ResponseDecodingFailed)
+ .attach_printable("Client error response received")
+ })?;
+ // let error = match status_code {
+ // 500 => ApiClientError::InternalServerErrorReceived,
+ // 502 => ApiClientError::BadGatewayReceived,
+ // 503 => ApiClientError::ServiceUnavailableReceived,
+ // 504 => ApiClientError::GatewayTimeoutReceived,
+ // _ => ApiClientError::UnexpectedServerResponse,
+ // };
+ Ok(Err(types::Response {
+ headers,
+ response: bytes,
+ status_code,
+ }))
+ }
+
+ status_code @ 400..=499 => {
+ let bytes = response.bytes().await.map_err(|error| {
+ report!(error)
+ .change_context(ApiClientError::ResponseDecodingFailed)
+ .attach_printable("Client error response received")
+ })?;
+ /* let error = match status_code {
+ 400 => ApiClientError::BadRequestReceived(bytes),
+ 401 => ApiClientError::UnauthorizedReceived(bytes),
+ 403 => ApiClientError::ForbiddenReceived,
+ 404 => ApiClientError::NotFoundReceived(bytes),
+ 405 => ApiClientError::MethodNotAllowedReceived,
+ 408 => ApiClientError::RequestTimeoutReceived,
+ 422 => ApiClientError::UnprocessableEntityReceived(bytes),
+ 429 => ApiClientError::TooManyRequestsReceived,
+ _ => ApiClientError::UnexpectedServerResponse,
+ };
+ Err(report!(error).attach_printable("Client error response received"))
+ */
+ Ok(Err(types::Response {
+ headers,
+ response: bytes,
+ status_code,
+ }))
+ }
+
+ _ => Err(report!(ApiClientError::UnexpectedServerResponse)
+ .attach_printable("Unexpected response from server")),
+ }
+ })?
+ .await
+}
+
+/// Store the raw connector response in the router data if required
+pub fn store_raw_connector_response_if_required<T, Req, Resp>(
+ return_raw_connector_response: Option<bool>,
+ router_data: &mut RouterData<T, Req, Resp>,
+ body: &types::Response,
+) -> CustomResult<(), ConnectorError>
+where
+ T: Clone + Debug + 'static,
+ Req: Debug + Clone + 'static,
+ Resp: Debug + Clone + 'static,
+{
+ if return_raw_connector_response == Some(true) {
+ let mut decoded = String::from_utf8(body.response.as_ref().to_vec())
+ .change_context(ConnectorError::ResponseDeserializationFailed)?;
+ if decoded.starts_with('\u{feff}') {
+ decoded = decoded.trim_start_matches('\u{feff}').to_string();
+ }
+ router_data.raw_connector_response = Some(masking::Secret::new(decoded));
+ }
+ Ok(())
+}
+
+/// Get the flow name from the type
+#[inline]
+pub fn get_flow_name<F>() -> CustomResult<String, api_error_response::ApiErrorResponse> {
+ Ok(std::any::type_name::<F>()
+ .to_string()
+ .rsplit("::")
+ .next()
+ .ok_or(api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("Flow stringify failed")?
+ .to_string())
+}
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 4b4594aebf..4e28441016 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -1 +1,191 @@
-pub use hyperswitch_domain_models::connector_endpoints::Connectors;
+use common_utils::{crypto::Encryptable, errors::CustomResult, id_type};
+pub use hyperswitch_domain_models::{
+ connector_endpoints::Connectors, errors::api_error_response, merchant_connector_account,
+};
+use masking::{PeekInterface, Secret};
+use serde::Deserialize;
+
+#[allow(missing_docs)]
+#[derive(Debug, Clone)]
+pub struct Tenant {
+ pub tenant_id: id_type::TenantId,
+ pub base_url: String,
+ pub schema: String,
+ pub accounts_schema: String,
+ pub redis_key_prefix: String,
+ pub clickhouse_database: String,
+ pub user: TenantUserConfig,
+}
+
+#[allow(missing_docs)]
+#[derive(Debug, Deserialize, Clone)]
+pub struct TenantUserConfig {
+ pub control_center_url: String,
+}
+
+impl common_utils::types::TenantConfig for Tenant {
+ fn get_tenant_id(&self) -> &id_type::TenantId {
+ &self.tenant_id
+ }
+ fn get_accounts_schema(&self) -> &str {
+ self.accounts_schema.as_str()
+ }
+ fn get_schema(&self) -> &str {
+ self.schema.as_str()
+ }
+ fn get_redis_key_prefix(&self) -> &str {
+ self.redis_key_prefix.as_str()
+ }
+ fn get_clickhouse_database(&self) -> &str {
+ self.clickhouse_database.as_str()
+ }
+}
+
+#[allow(missing_docs)]
+// Todo: Global tenant should not be part of tenant config(https://github.com/juspay/hyperswitch/issues/7237)
+#[derive(Debug, Deserialize, Clone)]
+pub struct GlobalTenant {
+ #[serde(default = "id_type::TenantId::get_default_global_tenant_id")]
+ pub tenant_id: id_type::TenantId,
+ pub schema: String,
+ pub redis_key_prefix: String,
+ pub clickhouse_database: String,
+}
+
+// Todo: Global tenant should not be part of tenant config
+impl common_utils::types::TenantConfig for GlobalTenant {
+ fn get_tenant_id(&self) -> &id_type::TenantId {
+ &self.tenant_id
+ }
+ fn get_accounts_schema(&self) -> &str {
+ self.schema.as_str()
+ }
+ fn get_schema(&self) -> &str {
+ self.schema.as_str()
+ }
+ fn get_redis_key_prefix(&self) -> &str {
+ self.redis_key_prefix.as_str()
+ }
+ fn get_clickhouse_database(&self) -> &str {
+ self.clickhouse_database.as_str()
+ }
+}
+
+impl Default for GlobalTenant {
+ fn default() -> Self {
+ Self {
+ tenant_id: id_type::TenantId::get_default_global_tenant_id(),
+ schema: String::from("global"),
+ redis_key_prefix: String::from("global"),
+ clickhouse_database: String::from("global"),
+ }
+ }
+}
+
+#[allow(missing_docs)]
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct InternalMerchantIdProfileIdAuthSettings {
+ pub enabled: bool,
+ pub internal_api_key: Secret<String>,
+}
+
+#[allow(missing_docs)]
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct InternalServicesConfig {
+ pub payments_base_url: String,
+}
+
+#[allow(missing_docs)]
+#[derive(Debug, Clone)]
+pub enum MerchantConnectorAccountType {
+ DbVal(Box<merchant_connector_account::MerchantConnectorAccount>),
+ CacheVal(api_models::admin::MerchantConnectorDetails),
+}
+
+#[allow(missing_docs)]
+impl MerchantConnectorAccountType {
+ pub fn get_metadata(&self) -> Option<Secret<serde_json::Value>> {
+ match self {
+ Self::DbVal(val) => val.metadata.to_owned(),
+ Self::CacheVal(val) => val.metadata.to_owned(),
+ }
+ }
+
+ pub fn get_connector_account_details(&self) -> serde_json::Value {
+ match self {
+ Self::DbVal(val) => val.connector_account_details.peek().to_owned(),
+ Self::CacheVal(val) => val.connector_account_details.peek().to_owned(),
+ }
+ }
+
+ pub fn get_connector_wallets_details(&self) -> Option<Secret<serde_json::Value>> {
+ match self {
+ Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(),
+ Self::CacheVal(_) => None,
+ }
+ }
+
+ pub fn is_disabled(&self) -> bool {
+ match self {
+ Self::DbVal(ref inner) => inner.disabled.unwrap_or(false),
+ // Cached merchant connector account, only contains the account details,
+ // the merchant connector account must only be cached if it's not disabled
+ Self::CacheVal(_) => false,
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ pub fn is_test_mode_on(&self) -> Option<bool> {
+ match self {
+ Self::DbVal(val) => val.test_mode,
+ Self::CacheVal(_) => None,
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ pub fn is_test_mode_on(&self) -> Option<bool> {
+ None
+ }
+
+ pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
+ match self {
+ Self::DbVal(db_val) => Some(db_val.get_id()),
+ Self::CacheVal(_) => None,
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ pub fn get_connector_name(&self) -> Option<String> {
+ match self {
+ Self::DbVal(db_val) => Some(db_val.connector_name.to_string()),
+ Self::CacheVal(_) => None,
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> {
+ match self {
+ Self::DbVal(db_val) => Some(db_val.connector_name),
+ Self::CacheVal(_) => None,
+ }
+ }
+
+ pub fn get_additional_merchant_data(&self) -> Option<Encryptable<Secret<serde_json::Value>>> {
+ match self {
+ Self::DbVal(db_val) => db_val.additional_merchant_data.clone(),
+ Self::CacheVal(_) => None,
+ }
+ }
+
+ pub fn get_webhook_details(
+ &self,
+ ) -> CustomResult<Option<&Secret<serde_json::Value>>, api_error_response::ApiErrorResponse>
+ {
+ match self {
+ Self::DbVal(db_val) => Ok(db_val.connector_webhook_details.as_ref()),
+ Self::CacheVal(_) => Ok(None),
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/consts.rs b/crates/hyperswitch_interfaces/src/consts.rs
index 2ac6ac3c10..ec9dc08ae7 100644
--- a/crates/hyperswitch_interfaces/src/consts.rs
+++ b/crates/hyperswitch_interfaces/src/consts.rs
@@ -11,3 +11,21 @@ pub const ACCEPT_HEADER: &str = "text/html,application/json";
/// User agent for request send from backend server
pub const USER_AGENT: &str = "Hyperswitch-Backend-Server";
+
+/// Request timeout error code
+pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT";
+
+/// error message for timed out request
+pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time";
+
+/// Header value indicating that signature-key-based authentication is used.
+pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key";
+
+/// Header value indicating that body-key-based authentication is used.
+pub const UCS_AUTH_BODY_KEY: &str = "body-key";
+
+/// Header value indicating that header-key-based authentication is used.
+pub const UCS_AUTH_HEADER_KEY: &str = "header-key";
+
+/// Header value indicating that currency-auth-key-based authentication is used.
+pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key";
diff --git a/crates/hyperswitch_interfaces/src/events.rs b/crates/hyperswitch_interfaces/src/events.rs
index 54f24c2ec1..c03ac35d32 100644
--- a/crates/hyperswitch_interfaces/src/events.rs
+++ b/crates/hyperswitch_interfaces/src/events.rs
@@ -1,4 +1,15 @@
-//! Events interface
+use crate::events::connector_api_logs::ConnectorEvent;
pub mod connector_api_logs;
pub mod routing_api_logs;
+
+/// Event handling interface
+#[async_trait::async_trait]
+pub trait EventHandlerInterface: dyn_clone::DynClone
+where
+ Self: Send + Sync,
+{
+ /// Logs connector events
+ #[track_caller]
+ fn log_connector_event(&self, event: &ConnectorEvent);
+}
diff --git a/crates/hyperswitch_interfaces/src/helpers.rs b/crates/hyperswitch_interfaces/src/helpers.rs
new file mode 100644
index 0000000000..9bde56eda6
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/helpers.rs
@@ -0,0 +1,7 @@
+/// Trait for converting from one foreign type to another
+pub trait ForeignTryFrom<F>: Sized {
+ /// Custom error for conversion failure
+ type Error;
+ /// Convert from a foreign type to the current type and return an error if the conversion fails
+ fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
+}
diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs
index b9c16f6d82..6f7fb34eae 100644
--- a/crates/hyperswitch_interfaces/src/lib.rs
+++ b/crates/hyperswitch_interfaces/src/lib.rs
@@ -2,6 +2,8 @@
#![warn(missing_docs, missing_debug_implementations)]
pub mod api;
+/// API client interface module
+pub mod api_client;
pub mod authentication;
/// Configuration related functionalities
pub mod configs;
@@ -16,12 +18,17 @@ pub mod conversion_impls;
pub mod disputes;
pub mod encryption_interface;
pub mod errors;
+/// Event handling interface
pub mod events;
+/// helper utils
+pub mod helpers;
/// connector integrity check interface
pub mod integrity;
pub mod metrics;
pub mod secrets_interface;
pub mod types;
+/// ucs handlers
+pub mod unified_connector_service;
pub mod webhooks;
/// Crm interface
diff --git a/crates/hyperswitch_interfaces/src/metrics.rs b/crates/hyperswitch_interfaces/src/metrics.rs
index 84aa6d10be..595cd5d49e 100644
--- a/crates/hyperswitch_interfaces/src/metrics.rs
+++ b/crates/hyperswitch_interfaces/src/metrics.rs
@@ -5,3 +5,10 @@ use router_env::{counter_metric, global_meter};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER);
+
+counter_metric!(CONNECTOR_CALL_COUNT, GLOBAL_METER); // Attributes needed
+
+counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER);
+counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER);
+// Connector Level Metric
+counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service.rs b/crates/hyperswitch_interfaces/src/unified_connector_service.rs
new file mode 100644
index 0000000000..be8d6cc7c8
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service.rs
@@ -0,0 +1,34 @@
+use common_enums::AttemptStatus;
+use common_utils::errors::CustomResult;
+use hyperswitch_domain_models::{
+ router_data::ErrorResponse, router_response_types::PaymentsResponseData,
+};
+use unified_connector_service_client::payments as payments_grpc;
+
+use crate::helpers::ForeignTryFrom;
+
+/// Unified Connector Service (UCS) related transformers
+pub mod transformers;
+
+pub use transformers::WebhookTransformData;
+
+/// Type alias for return type used by unified connector service response handlers
+type UnifiedConnectorServiceResult = CustomResult<
+ (
+ Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>,
+ u16,
+ ),
+ transformers::UnifiedConnectorServiceError,
+>;
+
+#[allow(missing_docs)]
+pub fn handle_unified_connector_service_response_for_payment_get(
+ response: payments_grpc::PaymentServiceGetResponse,
+) -> UnifiedConnectorServiceResult {
+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response =
+ Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
+
+ Ok((router_data_response, status_code))
+}
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
new file mode 100644
index 0000000000..128814f05a
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -0,0 +1,230 @@
+use common_enums::AttemptStatus;
+use hyperswitch_domain_models::{
+ router_data::ErrorResponse, router_response_types::PaymentsResponseData,
+};
+
+use crate::{helpers::ForeignTryFrom, unified_connector_service::payments_grpc};
+
+/// Unified Connector Service error variants
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum UnifiedConnectorServiceError {
+ /// Error occurred while communicating with the gRPC server.
+ #[error("Error from gRPC Server : {0}")]
+ ConnectionError(String),
+
+ /// Failed to encode the request to the unified connector service.
+ #[error("Failed to encode unified connector service request")]
+ RequestEncodingFailed,
+
+ /// Request encoding failed due to a specific reason.
+ #[error("Request encoding failed : {0}")]
+ RequestEncodingFailedWithReason(String),
+
+ /// Failed to deserialize the response from the connector.
+ #[error("Failed to deserialize connector response")]
+ ResponseDeserializationFailed,
+
+ /// The connector name provided is invalid or unrecognized.
+ #[error("An invalid connector name was provided")]
+ InvalidConnectorName,
+
+ /// Connector name is missing
+ #[error("Connector name is missing")]
+ MissingConnectorName,
+
+ /// A required field was missing in the request.
+ #[error("Missing required field: {field_name}")]
+ MissingRequiredField {
+ /// Missing Field
+ field_name: &'static str,
+ },
+
+ /// Multiple required fields were missing in the request.
+ #[error("Missing required fields: {field_names:?}")]
+ MissingRequiredFields {
+ /// Missing Fields
+ field_names: Vec<&'static str>,
+ },
+
+ /// The requested step or feature is not yet implemented.
+ #[error("This step has not been implemented for: {0}")]
+ NotImplemented(String),
+
+ /// Parsing of some value or input failed.
+ #[error("Parsing failed")]
+ ParsingFailed,
+
+ /// Data format provided is invalid
+ #[error("Invalid Data format")]
+ InvalidDataFormat {
+ /// Field Name for which data is invalid
+ field_name: &'static str,
+ },
+
+ /// Failed to obtain authentication type
+ #[error("Failed to obtain authentication type")]
+ FailedToObtainAuthType,
+
+ /// Failed to inject metadata into request headers
+ #[error("Failed to inject metadata into request headers: {0}")]
+ HeaderInjectionFailed(String),
+
+ /// Failed to perform Payment Authorize from gRPC Server
+ #[error("Failed to perform Payment Authorize from gRPC Server")]
+ PaymentAuthorizeFailure,
+
+ /// Failed to perform Payment Get from gRPC Server
+ #[error("Failed to perform Payment Get from gRPC Server")]
+ PaymentGetFailure,
+
+ /// Failed to perform Payment Setup Mandate from gRPC Server
+ #[error("Failed to perform Setup Mandate from gRPC Server")]
+ PaymentRegisterFailure,
+
+ /// Failed to perform Payment Repeat Payment from gRPC Server
+ #[error("Failed to perform Repeat Payment from gRPC Server")]
+ PaymentRepeatEverythingFailure,
+
+ /// Failed to transform incoming webhook from gRPC Server
+ #[error("Failed to transform incoming webhook from gRPC Server")]
+ WebhookTransformFailure,
+}
+
+#[allow(missing_docs)]
+/// Webhook transform data structure containing UCS response information
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct WebhookTransformData {
+ pub event_type: api_models::webhooks::IncomingWebhookEvent,
+ pub source_verified: bool,
+ pub webhook_content: Option<payments_grpc::WebhookResponseContent>,
+ pub response_ref_id: Option<String>,
+}
+
+impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse>
+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ response: payments_grpc::PaymentServiceGetResponse,
+ ) -> Result<Self, Self::Error> {
+ let connector_response_reference_id =
+ response.response_ref_id.as_ref().and_then(|identifier| {
+ identifier
+ .id_type
+ .clone()
+ .and_then(|id_type| match id_type {
+ payments_grpc::identifier::IdType::Id(id) => Some(id),
+ payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
+ Some(encoded_data)
+ }
+ payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
+ })
+ });
+
+ let status_code = convert_connector_service_status_code(response.status_code)?;
+
+ let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) {
+ Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id),
+ Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data),
+ Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId,
+ };
+
+ let response = if response.error_code.is_some() {
+ let attempt_status = match response.status() {
+ payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
+ _ => Some(AttemptStatus::foreign_try_from(response.status())?),
+ };
+
+ Err(ErrorResponse {
+ code: response.error_code().to_owned(),
+ message: response.error_message().to_owned(),
+ reason: Some(response.error_message().to_owned()),
+ status_code,
+ attempt_status,
+ connector_transaction_id: connector_response_reference_id,
+ network_decline_code: None,
+ network_advice_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ let status = AttemptStatus::foreign_try_from(response.status())?;
+
+ Ok((
+ PaymentsResponseData::TransactionResponse {
+ resource_id,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| {
+ hyperswitch_domain_models::router_response_types::MandateReference {
+ connector_mandate_id: grpc_mandate.mandate_id,
+ payment_method_id: None,
+ mandate_metadata: None,
+ connector_mandate_request_reference_id: None,
+ }
+ })),
+ connector_metadata: None,
+ network_txn_id: response.network_txn_id.clone(),
+ connector_response_reference_id,
+ incremental_authorization_allowed: None,
+ charges: None,
+ },
+ status,
+ ))
+ };
+
+ Ok(response)
+ }
+}
+
+impl ForeignTryFrom<payments_grpc::PaymentStatus> for AttemptStatus {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(grpc_status: payments_grpc::PaymentStatus) -> Result<Self, Self::Error> {
+ match grpc_status {
+ payments_grpc::PaymentStatus::Started => Ok(Self::Started),
+ payments_grpc::PaymentStatus::AuthenticationFailed => Ok(Self::AuthenticationFailed),
+ payments_grpc::PaymentStatus::RouterDeclined => Ok(Self::RouterDeclined),
+ payments_grpc::PaymentStatus::AuthenticationPending => Ok(Self::AuthenticationPending),
+ payments_grpc::PaymentStatus::AuthenticationSuccessful => {
+ Ok(Self::AuthenticationSuccessful)
+ }
+ payments_grpc::PaymentStatus::Authorized => Ok(Self::Authorized),
+ payments_grpc::PaymentStatus::AuthorizationFailed => Ok(Self::AuthorizationFailed),
+ payments_grpc::PaymentStatus::Charged => Ok(Self::Charged),
+ payments_grpc::PaymentStatus::Authorizing => Ok(Self::Authorizing),
+ payments_grpc::PaymentStatus::CodInitiated => Ok(Self::CodInitiated),
+ payments_grpc::PaymentStatus::Voided => Ok(Self::Voided),
+ payments_grpc::PaymentStatus::VoidInitiated => Ok(Self::VoidInitiated),
+ payments_grpc::PaymentStatus::CaptureInitiated => Ok(Self::CaptureInitiated),
+ payments_grpc::PaymentStatus::CaptureFailed => Ok(Self::CaptureFailed),
+ payments_grpc::PaymentStatus::VoidFailed => Ok(Self::VoidFailed),
+ payments_grpc::PaymentStatus::AutoRefunded => Ok(Self::AutoRefunded),
+ payments_grpc::PaymentStatus::PartialCharged => Ok(Self::PartialCharged),
+ payments_grpc::PaymentStatus::PartialChargedAndChargeable => {
+ Ok(Self::PartialChargedAndChargeable)
+ }
+ payments_grpc::PaymentStatus::Unresolved => Ok(Self::Unresolved),
+ payments_grpc::PaymentStatus::Pending => Ok(Self::Pending),
+ payments_grpc::PaymentStatus::Failure => Ok(Self::Failure),
+ payments_grpc::PaymentStatus::PaymentMethodAwaited => Ok(Self::PaymentMethodAwaited),
+ payments_grpc::PaymentStatus::ConfirmationAwaited => Ok(Self::ConfirmationAwaited),
+ payments_grpc::PaymentStatus::DeviceDataCollectionPending => {
+ Ok(Self::DeviceDataCollectionPending)
+ }
+ payments_grpc::PaymentStatus::AttemptStatusUnspecified => Ok(Self::Unresolved),
+ }
+ }
+}
+
+#[allow(missing_docs)]
+pub fn convert_connector_service_status_code(
+ status_code: u32,
+) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> {
+ u16::try_from(status_code).map_err(|err| {
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!(
+ "Failed to convert connector service status code to u16: {err}"
+ ))
+ .into()
+ })
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index b3486257ef..2a3cf49f6c 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -24,7 +24,7 @@ stripe = []
release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing", "payout_retry"]
oltp = ["storage_impl/oltp"]
kv_store = ["scheduler/kv_store"]
-accounts_cache = []
+accounts_cache = ["storage_impl/accounts_cache"]
vergen = ["router_env/vergen"]
dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "hyperswitch_interfaces/dummy_connector", "kgraph_utils/dummy_connector", "payment_methods/dummy_connector", "hyperswitch_domain_models/dummy_connector","hyperswitch_connectors/dummy_connector"]
external_access_dc = ["dummy_connector"]
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index dee7dfbb03..703631da6d 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -1,7 +1,5 @@
use std::collections::HashSet;
-use common_utils::id_type;
-
#[cfg(feature = "payouts")]
pub mod payout_required_fields;
@@ -124,17 +122,6 @@ impl Default for super::settings::KvConfig {
}
}
-impl Default for super::settings::GlobalTenant {
- fn default() -> Self {
- Self {
- tenant_id: id_type::TenantId::get_default_global_tenant_id(),
- schema: String::from("global"),
- redis_key_prefix: String::from("global"),
- clickhouse_database: String::from("global"),
- }
- }
-}
-
#[allow(clippy::derivable_impls)]
impl Default for super::settings::ApiKeys {
fn default() -> Self {
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 743c308192..13bcee2724 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -26,8 +26,11 @@ use external_services::{
},
superposition::SuperpositionClientConfig,
};
-pub use hyperswitch_interfaces::configs::Connectors;
-use hyperswitch_interfaces::{
+pub use hyperswitch_interfaces::{
+ configs::{
+ Connectors, GlobalTenant, InternalMerchantIdProfileIdAuthSettings, InternalServicesConfig,
+ Tenant, TenantUserConfig,
+ },
secrets_interface::secret_state::{
RawSecret, SecretState, SecretStateContainer, SecuredSecret,
},
@@ -345,68 +348,6 @@ pub struct L2L3DataConfig {
pub enabled: bool,
}
-#[derive(Debug, Clone)]
-pub struct Tenant {
- pub tenant_id: id_type::TenantId,
- pub base_url: String,
- pub schema: String,
- pub accounts_schema: String,
- pub redis_key_prefix: String,
- pub clickhouse_database: String,
- pub user: TenantUserConfig,
-}
-
-#[derive(Debug, Deserialize, Clone)]
-pub struct TenantUserConfig {
- pub control_center_url: String,
-}
-
-impl storage_impl::config::TenantConfig for Tenant {
- fn get_tenant_id(&self) -> &id_type::TenantId {
- &self.tenant_id
- }
- fn get_accounts_schema(&self) -> &str {
- self.accounts_schema.as_str()
- }
- fn get_schema(&self) -> &str {
- self.schema.as_str()
- }
- fn get_redis_key_prefix(&self) -> &str {
- self.redis_key_prefix.as_str()
- }
- fn get_clickhouse_database(&self) -> &str {
- self.clickhouse_database.as_str()
- }
-}
-
-// Todo: Global tenant should not be part of tenant config(https://github.com/juspay/hyperswitch/issues/7237)
-#[derive(Debug, Deserialize, Clone)]
-pub struct GlobalTenant {
- #[serde(default = "id_type::TenantId::get_default_global_tenant_id")]
- pub tenant_id: id_type::TenantId,
- pub schema: String,
- pub redis_key_prefix: String,
- pub clickhouse_database: String,
-}
-// Todo: Global tenant should not be part of tenant config
-impl storage_impl::config::TenantConfig for GlobalTenant {
- fn get_tenant_id(&self) -> &id_type::TenantId {
- &self.tenant_id
- }
- fn get_accounts_schema(&self) -> &str {
- self.schema.as_str()
- }
- fn get_schema(&self) -> &str {
- self.schema.as_str()
- }
- fn get_redis_key_prefix(&self) -> &str {
- self.redis_key_prefix.as_str()
- }
- fn get_clickhouse_database(&self) -> &str {
- self.clickhouse_database.as_str()
- }
-}
-
#[derive(Debug, Deserialize, Clone, Default)]
pub struct UnmaskedHeaders {
#[serde(deserialize_with = "deserialize_hashset")]
@@ -872,13 +813,6 @@ pub struct MerchantIdAuthSettings {
pub merchant_id_auth_enabled: bool,
}
-#[derive(Debug, Clone, Default, Deserialize)]
-#[serde(default)]
-pub struct InternalMerchantIdProfileIdAuthSettings {
- pub enabled: bool,
- pub internal_api_key: Secret<String>,
-}
-
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ProxyStatusMapping {
@@ -987,12 +921,6 @@ pub struct NetworkTokenizationSupportedConnectors {
pub connector_list: HashSet<enums::Connector>,
}
-#[derive(Debug, Deserialize, Clone, Default)]
-#[serde(default)]
-pub struct InternalServicesConfig {
- pub payments_base_url: String,
-}
-
impl Settings<SecuredSecret> {
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs
index 08e3195559..3edc2436b4 100644
--- a/crates/router/src/core/payments/customers.rs
+++ b/crates/router/src/core/payments/customers.rs
@@ -1,6 +1,5 @@
-use common_utils::pii;
+pub use hyperswitch_domain_models::customer::update_connector_customer_in_customers;
use hyperswitch_interfaces::api::ConnectorSpecifications;
-use masking::ExposeOptionInterface;
use router_env::{instrument, tracing};
use crate::{
@@ -11,7 +10,7 @@ use crate::{
logger,
routes::{metrics, SessionState},
services,
- types::{self, api, domain, storage},
+ types::{self, api, domain},
};
#[instrument(skip_all)]
@@ -130,57 +129,3 @@ pub fn should_call_connector_create_customer<'a>(
}
}
}
-
-#[cfg(feature = "v1")]
-#[instrument]
-pub async fn update_connector_customer_in_customers(
- connector_label: &str,
- customer: Option<&domain::Customer>,
- connector_customer_id: Option<String>,
-) -> Option<storage::CustomerUpdate> {
- let mut connector_customer_map = customer
- .and_then(|customer| customer.connector_customer.clone().expose_option())
- .and_then(|connector_customer| connector_customer.as_object().cloned())
- .unwrap_or_default();
-
- let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| {
- let connector_customer_value = serde_json::Value::String(connector_customer_id);
- connector_customer_map.insert(connector_label.to_string(), connector_customer_value);
- connector_customer_map
- });
-
- updated_connector_customer_map
- .map(serde_json::Value::Object)
- .map(
- |connector_customer_value| storage::CustomerUpdate::ConnectorCustomer {
- connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)),
- },
- )
-}
-
-#[cfg(feature = "v2")]
-#[instrument]
-pub async fn update_connector_customer_in_customers(
- merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
- customer: Option<&domain::Customer>,
- connector_customer_id: Option<String>,
-) -> Option<storage::CustomerUpdate> {
- match merchant_connector_account {
- domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
- connector_customer_id.map(|new_conn_cust_id| {
- let connector_account_id = account.get_id().clone();
- let mut connector_customer_map = customer
- .and_then(|customer| customer.connector_customer.clone())
- .unwrap_or_default();
- connector_customer_map.insert(connector_account_id, new_conn_cust_id);
- storage::CustomerUpdate::ConnectorCustomer {
- connector_customer: Some(connector_customer_map),
- }
- })
- }
- // TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
- domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
- todo!("Handle connector_customer construction for MerchantConnectorDetails");
- }
- }
-}
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index e54a5fd173..8525fc8557 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -6,6 +6,7 @@ use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
use hyperswitch_domain_models::payments as domain_payments;
+use hyperswitch_interfaces::unified_connector_service::handle_unified_connector_service_response_for_payment_get;
use masking::Secret;
use unified_connector_service_client::payments as payments_grpc;
@@ -16,8 +17,7 @@ use crate::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
unified_connector_service::{
- build_unified_connector_service_auth_metadata,
- handle_unified_connector_service_response_for_payment_get, ucs_logging_wrapper,
+ build_unified_connector_service_auth_metadata, ucs_logging_wrapper,
},
},
routes::SessionState,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 601d9bc5f9..84b8bed45b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -41,8 +41,9 @@ use hyperswitch_domain_models::{
},
router_data::KlarnaSdkResponse,
};
-use hyperswitch_interfaces::{
+pub use hyperswitch_interfaces::{
api::ConnectorSpecifications,
+ configs::MerchantConnectorAccountType,
integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject},
};
use josekit::jwe;
@@ -4247,98 +4248,6 @@ pub async fn insert_merchant_connector_creds_to_config(
}
}
-#[derive(Clone)]
-pub enum MerchantConnectorAccountType {
- DbVal(Box<domain::MerchantConnectorAccount>),
- CacheVal(api_models::admin::MerchantConnectorDetails),
-}
-
-impl MerchantConnectorAccountType {
- pub fn get_metadata(&self) -> Option<masking::Secret<serde_json::Value>> {
- match self {
- Self::DbVal(val) => val.metadata.to_owned(),
- Self::CacheVal(val) => val.metadata.to_owned(),
- }
- }
-
- pub fn get_connector_account_details(&self) -> serde_json::Value {
- match self {
- Self::DbVal(val) => val.connector_account_details.peek().to_owned(),
- Self::CacheVal(val) => val.connector_account_details.peek().to_owned(),
- }
- }
-
- pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> {
- match self {
- Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(),
- Self::CacheVal(_) => None,
- }
- }
-
- pub fn is_disabled(&self) -> bool {
- match self {
- Self::DbVal(ref inner) => inner.disabled.unwrap_or(false),
- // Cached merchant connector account, only contains the account details,
- // the merchant connector account must only be cached if it's not disabled
- Self::CacheVal(_) => false,
- }
- }
-
- #[cfg(feature = "v1")]
- pub fn is_test_mode_on(&self) -> Option<bool> {
- match self {
- Self::DbVal(val) => val.test_mode,
- Self::CacheVal(_) => None,
- }
- }
-
- #[cfg(feature = "v2")]
- pub fn is_test_mode_on(&self) -> Option<bool> {
- None
- }
-
- pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
- match self {
- Self::DbVal(db_val) => Some(db_val.get_id()),
- Self::CacheVal(_) => None,
- }
- }
-
- #[cfg(feature = "v1")]
- pub fn get_connector_name(&self) -> Option<String> {
- match self {
- Self::DbVal(db_val) => Some(db_val.connector_name.to_string()),
- Self::CacheVal(_) => None,
- }
- }
-
- #[cfg(feature = "v2")]
- pub fn get_connector_name(&self) -> Option<api_enums::Connector> {
- match self {
- Self::DbVal(db_val) => Some(db_val.connector_name),
- Self::CacheVal(_) => None,
- }
- }
-
- pub fn get_additional_merchant_data(
- &self,
- ) -> Option<Encryptable<masking::Secret<serde_json::Value>>> {
- match self {
- Self::DbVal(db_val) => db_val.additional_merchant_data.clone(),
- Self::CacheVal(_) => None,
- }
- }
-
- pub fn get_webhook_details(
- &self,
- ) -> CustomResult<Option<&masking::Secret<serde_json::Value>>, errors::ApiErrorResponse> {
- match self {
- Self::DbVal(db_val) => Ok(db_val.connector_webhook_details.as_ref()),
- Self::CacheVal(_) => Ok(None),
- }
- }
-}
-
/// Query for merchant connector account either by business label or profile id
/// If profile_id is passed use it, or use connector_label to query merchant connector account
#[instrument(skip_all)]
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index d2848d34e4..255256b89b 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -756,17 +756,6 @@ pub fn handle_unified_connector_service_response_for_payment_authorize(
Ok((router_data_response, status_code))
}
-pub fn handle_unified_connector_service_response_for_payment_get(
- response: payments_grpc::PaymentServiceGetResponse,
-) -> UnifiedConnectorServiceResult {
- let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
-
- let router_data_response =
- Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
-
- Ok((router_data_response, status_code))
-}
-
pub fn handle_unified_connector_service_response_for_payment_register(
response: payments_grpc::PaymentServiceRegisterResponse,
) -> UnifiedConnectorServiceResult {
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index 357771fbb2..28de14d090 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -17,6 +17,12 @@ use hyperswitch_domain_models::{
},
router_response_types::{PaymentsResponseData, RedirectForm},
};
+pub use hyperswitch_interfaces::{
+ helpers::ForeignTryFrom,
+ unified_connector_service::{
+ transformers::convert_connector_service_status_code, WebhookTransformData,
+ },
+};
use masking::{ExposeInterface, PeekInterface};
use router_env::tracing;
use unified_connector_service_client::payments::{
@@ -27,9 +33,9 @@ use url::Url;
use crate::{
core::{errors, unified_connector_service},
- types::transformers::ForeignTryFrom,
+ types::transformers,
};
-impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>>
+impl transformers::ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>>
for payments_grpc::PaymentServiceGetRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -81,8 +87,10 @@ impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>>
}
}
-impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>
- for payments_grpc::PaymentServiceAuthorizeRequest
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
+ > for payments_grpc::PaymentServiceAuthorizeRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -200,7 +208,7 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon
}
impl
- ForeignTryFrom<
+ transformers::ForeignTryFrom<
&RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>,
> for payments_grpc::PaymentServiceAuthorizeRequest
{
@@ -329,8 +337,10 @@ impl
}
}
-impl ForeignTryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>>
- for payments_grpc::PaymentServiceRegisterRequest
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ > for payments_grpc::PaymentServiceRegisterRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -433,8 +443,10 @@ impl ForeignTryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsR
}
}
-impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>
- for payments_grpc::PaymentServiceRepeatEverythingRequest
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
+ > for payments_grpc::PaymentServiceRepeatEverythingRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -513,7 +525,7 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon
}
}
-impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse>
+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -609,84 +621,7 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse>
}
}
-impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse>
- for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
-{
- type Error = error_stack::Report<UnifiedConnectorServiceError>;
-
- fn foreign_try_from(
- response: payments_grpc::PaymentServiceGetResponse,
- ) -> Result<Self, Self::Error> {
- let connector_response_reference_id =
- response.response_ref_id.as_ref().and_then(|identifier| {
- identifier
- .id_type
- .clone()
- .and_then(|id_type| match id_type {
- payments_grpc::identifier::IdType::Id(id) => Some(id),
- payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
- Some(encoded_data)
- }
- payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
- })
- });
-
- let status_code = convert_connector_service_status_code(response.status_code)?;
-
- let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) {
- Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id),
- Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data),
- Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId,
- };
-
- let response = if response.error_code.is_some() {
- let attempt_status = match response.status() {
- payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
- _ => Some(AttemptStatus::foreign_try_from(response.status())?),
- };
-
- Err(ErrorResponse {
- code: response.error_code().to_owned(),
- message: response.error_message().to_owned(),
- reason: Some(response.error_message().to_owned()),
- status_code,
- attempt_status,
- connector_transaction_id: connector_response_reference_id,
- network_decline_code: None,
- network_advice_code: None,
- network_error_message: None,
- connector_metadata: None,
- })
- } else {
- let status = AttemptStatus::foreign_try_from(response.status())?;
-
- Ok((
- PaymentsResponseData::TransactionResponse {
- resource_id,
- redirection_data: Box::new(None),
- mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| {
- hyperswitch_domain_models::router_response_types::MandateReference {
- connector_mandate_id: grpc_mandate.mandate_id,
- payment_method_id: None,
- mandate_metadata: None,
- connector_mandate_request_reference_id: None,
- }
- })),
- connector_metadata: None,
- network_txn_id: response.network_txn_id.clone(),
- connector_response_reference_id,
- incremental_authorization_allowed: None,
- charges: None,
- },
- status,
- ))
- };
-
- Ok(response)
- }
-}
-
-impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse>
+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -774,7 +709,7 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse>
}
}
-impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse>
+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -845,7 +780,7 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse>
}
}
-impl ForeignTryFrom<common_enums::Currency> for payments_grpc::Currency {
+impl transformers::ForeignTryFrom<common_enums::Currency> for payments_grpc::Currency {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(currency: common_enums::Currency) -> Result<Self, Self::Error> {
@@ -858,7 +793,7 @@ impl ForeignTryFrom<common_enums::Currency> for payments_grpc::Currency {
}
}
-impl ForeignTryFrom<common_enums::CardNetwork> for payments_grpc::CardNetwork {
+impl transformers::ForeignTryFrom<common_enums::CardNetwork> for payments_grpc::CardNetwork {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(card_network: common_enums::CardNetwork) -> Result<Self, Self::Error> {
@@ -883,7 +818,7 @@ impl ForeignTryFrom<common_enums::CardNetwork> for payments_grpc::CardNetwork {
}
}
-impl ForeignTryFrom<hyperswitch_domain_models::payment_address::PaymentAddress>
+impl transformers::ForeignTryFrom<hyperswitch_domain_models::payment_address::PaymentAddress>
for payments_grpc::PaymentAddress
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -1005,7 +940,7 @@ impl ForeignTryFrom<hyperswitch_domain_models::payment_address::PaymentAddress>
}
}
-impl ForeignTryFrom<AuthenticationType> for payments_grpc::AuthenticationType {
+impl transformers::ForeignTryFrom<AuthenticationType> for payments_grpc::AuthenticationType {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(auth_type: AuthenticationType) -> Result<Self, Self::Error> {
@@ -1016,8 +951,10 @@ impl ForeignTryFrom<AuthenticationType> for payments_grpc::AuthenticationType {
}
}
-impl ForeignTryFrom<hyperswitch_domain_models::router_request_types::BrowserInformation>
- for payments_grpc::BrowserInformation
+impl
+ transformers::ForeignTryFrom<
+ hyperswitch_domain_models::router_request_types::BrowserInformation,
+ > for payments_grpc::BrowserInformation
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -1044,7 +981,7 @@ impl ForeignTryFrom<hyperswitch_domain_models::router_request_types::BrowserInfo
}
}
-impl ForeignTryFrom<storage_enums::CaptureMethod> for payments_grpc::CaptureMethod {
+impl transformers::ForeignTryFrom<storage_enums::CaptureMethod> for payments_grpc::CaptureMethod {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(capture_method: storage_enums::CaptureMethod) -> Result<Self, Self::Error> {
@@ -1058,7 +995,7 @@ impl ForeignTryFrom<storage_enums::CaptureMethod> for payments_grpc::CaptureMeth
}
}
-impl ForeignTryFrom<AuthenticationData> for payments_grpc::AuthenticationData {
+impl transformers::ForeignTryFrom<AuthenticationData> for payments_grpc::AuthenticationData {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(authentication_data: AuthenticationData) -> Result<Self, Self::Error> {
@@ -1076,47 +1013,7 @@ impl ForeignTryFrom<AuthenticationData> for payments_grpc::AuthenticationData {
}
}
-impl ForeignTryFrom<payments_grpc::PaymentStatus> for AttemptStatus {
- type Error = error_stack::Report<UnifiedConnectorServiceError>;
-
- fn foreign_try_from(grpc_status: payments_grpc::PaymentStatus) -> Result<Self, Self::Error> {
- match grpc_status {
- payments_grpc::PaymentStatus::Started => Ok(Self::Started),
- payments_grpc::PaymentStatus::AuthenticationFailed => Ok(Self::AuthenticationFailed),
- payments_grpc::PaymentStatus::RouterDeclined => Ok(Self::RouterDeclined),
- payments_grpc::PaymentStatus::AuthenticationPending => Ok(Self::AuthenticationPending),
- payments_grpc::PaymentStatus::AuthenticationSuccessful => {
- Ok(Self::AuthenticationSuccessful)
- }
- payments_grpc::PaymentStatus::Authorized => Ok(Self::Authorized),
- payments_grpc::PaymentStatus::AuthorizationFailed => Ok(Self::AuthorizationFailed),
- payments_grpc::PaymentStatus::Charged => Ok(Self::Charged),
- payments_grpc::PaymentStatus::Authorizing => Ok(Self::Authorizing),
- payments_grpc::PaymentStatus::CodInitiated => Ok(Self::CodInitiated),
- payments_grpc::PaymentStatus::Voided => Ok(Self::Voided),
- payments_grpc::PaymentStatus::VoidInitiated => Ok(Self::VoidInitiated),
- payments_grpc::PaymentStatus::CaptureInitiated => Ok(Self::CaptureInitiated),
- payments_grpc::PaymentStatus::CaptureFailed => Ok(Self::CaptureFailed),
- payments_grpc::PaymentStatus::VoidFailed => Ok(Self::VoidFailed),
- payments_grpc::PaymentStatus::AutoRefunded => Ok(Self::AutoRefunded),
- payments_grpc::PaymentStatus::PartialCharged => Ok(Self::PartialCharged),
- payments_grpc::PaymentStatus::PartialChargedAndChargeable => {
- Ok(Self::PartialChargedAndChargeable)
- }
- payments_grpc::PaymentStatus::Unresolved => Ok(Self::Unresolved),
- payments_grpc::PaymentStatus::Pending => Ok(Self::Pending),
- payments_grpc::PaymentStatus::Failure => Ok(Self::Failure),
- payments_grpc::PaymentStatus::PaymentMethodAwaited => Ok(Self::PaymentMethodAwaited),
- payments_grpc::PaymentStatus::ConfirmationAwaited => Ok(Self::ConfirmationAwaited),
- payments_grpc::PaymentStatus::DeviceDataCollectionPending => {
- Ok(Self::DeviceDataCollectionPending)
- }
- payments_grpc::PaymentStatus::AttemptStatusUnspecified => Ok(Self::Unresolved),
- }
- }
-}
-
-impl ForeignTryFrom<payments_grpc::RedirectForm> for RedirectForm {
+impl transformers::ForeignTryFrom<payments_grpc::RedirectForm> for RedirectForm {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(value: payments_grpc::RedirectForm) -> Result<Self, Self::Error> {
@@ -1145,7 +1042,7 @@ impl ForeignTryFrom<payments_grpc::RedirectForm> for RedirectForm {
}
}
-impl ForeignTryFrom<payments_grpc::HttpMethod> for Method {
+impl transformers::ForeignTryFrom<payments_grpc::HttpMethod> for Method {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(value: payments_grpc::HttpMethod) -> Result<Self, Self::Error> {
@@ -1163,7 +1060,7 @@ impl ForeignTryFrom<payments_grpc::HttpMethod> for Method {
}
}
-impl ForeignTryFrom<storage_enums::FutureUsage> for payments_grpc::FutureUsage {
+impl transformers::ForeignTryFrom<storage_enums::FutureUsage> for payments_grpc::FutureUsage {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(future_usage: storage_enums::FutureUsage) -> Result<Self, Self::Error> {
@@ -1174,7 +1071,7 @@ impl ForeignTryFrom<storage_enums::FutureUsage> for payments_grpc::FutureUsage {
}
}
-impl ForeignTryFrom<common_types::payments::CustomerAcceptance>
+impl transformers::ForeignTryFrom<common_types::payments::CustomerAcceptance>
for payments_grpc::CustomerAcceptance
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -1208,8 +1105,10 @@ impl ForeignTryFrom<common_types::payments::CustomerAcceptance>
}
}
-impl ForeignTryFrom<&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>>
- for payments_grpc::RequestDetails
+impl
+ transformers::ForeignTryFrom<
+ &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
+ > for payments_grpc::RequestDetails
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
@@ -1252,15 +1151,6 @@ impl ForeignTryFrom<&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDet
}
}
-/// Webhook transform data structure containing UCS response information
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct WebhookTransformData {
- pub event_type: api_models::webhooks::IncomingWebhookEvent,
- pub source_verified: bool,
- pub webhook_content: Option<payments_grpc::WebhookResponseContent>,
- pub response_ref_id: Option<String>,
-}
-
/// Transform UCS webhook response into webhook event data
pub fn transform_ucs_webhook_response(
response: PaymentServiceTransformResponse,
@@ -1290,7 +1180,10 @@ pub fn build_webhook_transform_request(
merchant_id: &str,
connector_id: &str,
) -> Result<PaymentServiceTransformRequest, error_stack::Report<errors::ApiErrorResponse>> {
- let request_details_grpc = payments_grpc::RequestDetails::foreign_try_from(request_details)
+ let request_details_grpc =
+ <payments_grpc::RequestDetails as transformers::ForeignTryFrom<_>>::foreign_try_from(
+ request_details,
+ )
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to transform webhook request details to gRPC format")?;
@@ -1308,14 +1201,3 @@ pub fn build_webhook_transform_request(
access_token: None,
})
}
-
-pub fn convert_connector_service_status_code(
- status_code: u32,
-) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> {
- u16::try_from(status_code).map_err(|err| {
- UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!(
- "Failed to convert connector service status code to u16: {err}"
- ))
- .into()
- })
-}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 4aef4efd3e..bc307de04f 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -97,7 +97,7 @@ pub trait StorageInterface:
+ address::AddressInterface
+ api_keys::ApiKeyInterface
+ blocklist_lookup::BlocklistLookupInterface
- + configs::ConfigInterface
+ + configs::ConfigInterface<Error = StorageError>
+ capture::CaptureInterface
+ customers::CustomerInterface<Error = StorageError>
+ dashboard_metadata::DashboardMetadataInterface
@@ -109,9 +109,9 @@ pub trait StorageInterface:
+ FraudCheckInterface
+ locker_mock_up::LockerMockUpInterface
+ mandate::MandateInterface
- + merchant_account::MerchantAccountInterface
+ + merchant_account::MerchantAccountInterface<Error = StorageError>
+ merchant_connector_account::ConnectorAccessToken
- + merchant_connector_account::MerchantConnectorAccountInterface
+ + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>
+ PaymentAttemptInterface<Error = StorageError>
+ PaymentIntentInterface<Error = StorageError>
+ PaymentMethodInterface<Error = StorageError>
@@ -124,12 +124,12 @@ pub trait StorageInterface:
+ refund::RefundInterface
+ reverse_lookup::ReverseLookupInterface
+ CardsInfoInterface<Error = StorageError>
- + merchant_key_store::MerchantKeyStoreInterface
+ + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>
+ MasterKeyInterface
+ payment_link::PaymentLinkInterface
+ RedisConnInterface
+ RequestIdStore
- + business_profile::ProfileInterface
+ + business_profile::ProfileInterface<Error = StorageError>
+ routing_algorithm::RoutingAlgorithmInterface
+ gsm::GsmInterface
+ unified_translations::UnifiedTranslationsInterface
@@ -175,10 +175,10 @@ pub trait AccountsStorageInterface:
+ Sync
+ dyn_clone::DynClone
+ OrganizationInterface
- + merchant_account::MerchantAccountInterface
- + business_profile::ProfileInterface
- + merchant_connector_account::MerchantConnectorAccountInterface
- + merchant_key_store::MerchantKeyStoreInterface
+ + merchant_account::MerchantAccountInterface<Error = StorageError>
+ + business_profile::ProfileInterface<Error = StorageError>
+ + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>
+ + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>
+ dashboard_metadata::DashboardMetadataInterface
+ 'static
{
diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs
index 1a087c2903..ecd8b75610 100644
--- a/crates/router/src/db/business_profile.rs
+++ b/crates/router/src/db/business_profile.rs
@@ -1,453 +1,4 @@
-use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};
-use error_stack::{report, ResultExt};
-use router_env::{instrument, tracing};
-
-use super::Store;
-use crate::{
- connection,
- core::errors::{self, CustomResult},
- db::MockDb,
- types::{
- domain::{
- self,
- behaviour::{Conversion, ReverseConversion},
- },
- storage,
- },
+pub use hyperswitch_domain_models::{
+ business_profile::{self, ProfileInterface},
+ errors::api_error_response,
};
-
-#[async_trait::async_trait]
-pub trait ProfileInterface
-where
- domain::Profile: Conversion<DstType = storage::Profile, NewDstType = storage::ProfileNew>,
-{
- async fn insert_business_profile(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- business_profile: domain::Profile,
- ) -> CustomResult<domain::Profile, errors::StorageError>;
-
- async fn find_business_profile_by_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- profile_id: &common_utils::id_type::ProfileId,
- ) -> CustomResult<domain::Profile, errors::StorageError>;
-
- async fn find_business_profile_by_merchant_id_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
- profile_id: &common_utils::id_type::ProfileId,
- ) -> CustomResult<domain::Profile, errors::StorageError>;
-
- async fn find_business_profile_by_profile_name_merchant_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- profile_name: &str,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<domain::Profile, errors::StorageError>;
-
- async fn update_profile_by_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- current_state: domain::Profile,
- profile_update: domain::ProfileUpdate,
- ) -> CustomResult<domain::Profile, errors::StorageError>;
-
- async fn delete_profile_by_profile_id_merchant_id(
- &self,
- profile_id: &common_utils::id_type::ProfileId,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError>;
-
- async fn list_profile_by_merchant_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<Vec<domain::Profile>, errors::StorageError>;
-}
-
-#[async_trait::async_trait]
-impl ProfileInterface for Store {
- #[instrument(skip_all)]
- async fn insert_business_profile(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- business_profile: domain::Profile,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- business_profile
- .construct_new()
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .insert(&conn)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn find_business_profile_by_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- profile_id: &common_utils::id_type::ProfileId,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::Profile::find_by_profile_id(&conn, profile_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- async fn find_business_profile_by_merchant_id_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
- profile_id: &common_utils::id_type::ProfileId,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::Profile::find_by_merchant_id_profile_id(&conn, merchant_id, profile_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn find_business_profile_by_profile_name_merchant_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- profile_name: &str,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::Profile::find_by_profile_name_merchant_id(&conn, profile_name, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn update_profile_by_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- current_state: domain::Profile,
- profile_update: domain::ProfileUpdate,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- Conversion::convert(current_state)
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .update_by_profile_id(&conn, storage::ProfileUpdateInternal::from(profile_update))
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn delete_profile_by_profile_id_merchant_id(
- &self,
- profile_id: &common_utils::id_type::ProfileId,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- storage::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn list_profile_by_merchant_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<Vec<domain::Profile>, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::Profile::list_profile_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|business_profiles| async {
- let mut domain_business_profiles = Vec::with_capacity(business_profiles.len());
- for business_profile in business_profiles.into_iter() {
- domain_business_profiles.push(
- business_profile
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- );
- }
- Ok(domain_business_profiles)
- })
- .await
- }
-}
-
-#[async_trait::async_trait]
-impl ProfileInterface for MockDb {
- async fn insert_business_profile(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- business_profile: domain::Profile,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let stored_business_profile = Conversion::convert(business_profile)
- .await
- .change_context(errors::StorageError::EncryptionError)?;
-
- self.business_profiles
- .lock()
- .await
- .push(stored_business_profile.clone());
-
- stored_business_profile
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- async fn find_business_profile_by_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- profile_id: &common_utils::id_type::ProfileId,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- self.business_profiles
- .lock()
- .await
- .iter()
- .find(|business_profile| business_profile.get_id() == profile_id)
- .cloned()
- .async_map(|business_profile| async {
- business_profile
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "No business profile found for profile_id = {profile_id:?}"
- ))
- .into(),
- )
- }
-
- async fn find_business_profile_by_merchant_id_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
- profile_id: &common_utils::id_type::ProfileId,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- self.business_profiles
- .lock()
- .await
- .iter()
- .find(|business_profile| {
- business_profile.merchant_id == *merchant_id
- && business_profile.get_id() == profile_id
- })
- .cloned()
- .async_map(|business_profile| async {
- business_profile
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}"
- ))
- .into(),
- )
- }
-
- async fn update_profile_by_profile_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- current_state: domain::Profile,
- profile_update: domain::ProfileUpdate,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- let profile_id = current_state.get_id().to_owned();
- self.business_profiles
- .lock()
- .await
- .iter_mut()
- .find(|business_profile| business_profile.get_id() == current_state.get_id())
- .async_map(|business_profile| async {
- let profile_updated = storage::ProfileUpdateInternal::from(profile_update)
- .apply_changeset(
- Conversion::convert(current_state)
- .await
- .change_context(errors::StorageError::EncryptionError)?,
- );
- *business_profile = profile_updated.clone();
-
- profile_updated
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "No business profile found for profile_id = {profile_id:?}",
- ))
- .into(),
- )
- }
-
- async fn delete_profile_by_profile_id_merchant_id(
- &self,
- profile_id: &common_utils::id_type::ProfileId,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError> {
- let mut business_profiles = self.business_profiles.lock().await;
- let index = business_profiles
- .iter()
- .position(|business_profile| {
- business_profile.get_id() == profile_id
- && business_profile.merchant_id == *merchant_id
- })
- .ok_or::<errors::StorageError>(errors::StorageError::ValueNotFound(format!(
- "No business profile found for profile_id = {profile_id:?} and merchant_id = {merchant_id:?}"
- )))?;
- business_profiles.remove(index);
- Ok(true)
- }
-
- async fn list_profile_by_merchant_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<Vec<domain::Profile>, errors::StorageError> {
- let business_profiles = self
- .business_profiles
- .lock()
- .await
- .iter()
- .filter(|business_profile| business_profile.merchant_id == *merchant_id)
- .cloned()
- .collect::<Vec<_>>();
-
- let mut domain_business_profiles = Vec::with_capacity(business_profiles.len());
-
- for business_profile in business_profiles {
- let domain_profile = business_profile
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?;
- domain_business_profiles.push(domain_profile);
- }
-
- Ok(domain_business_profiles)
- }
-
- async fn find_business_profile_by_profile_name_merchant_id(
- &self,
- key_manager_state: &KeyManagerState,
- merchant_key_store: &domain::MerchantKeyStore,
- profile_name: &str,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<domain::Profile, errors::StorageError> {
- self.business_profiles
- .lock()
- .await
- .iter()
- .find(|business_profile| {
- business_profile.profile_name == profile_name
- && business_profile.merchant_id == *merchant_id
- })
- .cloned()
- .async_map(|business_profile| async {
- business_profile
- .convert(
- key_manager_state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}"
-
- ))
- .into(),
- )
- }
-}
diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs
index 2ffea09939..dadb55f2cf 100644
--- a/crates/router/src/db/configs.rs
+++ b/crates/router/src/db/configs.rs
@@ -1,277 +1,4 @@
-use diesel_models::configs::ConfigUpdateInternal;
-use error_stack::report;
-use router_env::{instrument, tracing};
-use storage_impl::redis::cache::{self, CacheKind, CONFIG_CACHE};
-
-use super::{MockDb, Store};
-use crate::{
- connection,
- core::errors::{self, CustomResult},
- db::StorageInterface,
- types::storage,
+pub use hyperswitch_domain_models::{
+ configs::{self, ConfigInterface},
+ errors::api_error_response,
};
-
-#[async_trait::async_trait]
-pub trait ConfigInterface {
- async fn insert_config(
- &self,
- config: storage::ConfigNew,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-
- async fn find_config_by_key(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-
- async fn find_config_by_key_unwrap_or(
- &self,
- key: &str,
- // If the config is not found it will be created with the default value.
- default_config: Option<String>,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-
- async fn find_config_by_key_from_db(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-
- async fn update_config_by_key(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-
- async fn delete_config_by_key(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError>;
-}
-
-#[async_trait::async_trait]
-impl ConfigInterface for Store {
- #[instrument(skip_all)]
- async fn insert_config(
- &self,
- config: storage::ConfigNew,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- let inserted = config
- .insert(&conn)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- cache::redact_from_redis_and_publish(
- self.get_cache_store().as_ref(),
- [CacheKind::Config((&inserted.key).into())],
- )
- .await?;
-
- Ok(inserted)
- }
-
- #[instrument(skip_all)]
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::Config::update_by_key(&conn, key, config_update)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- //update in DB and remove in redis and cache
- #[instrument(skip_all)]
- async fn update_config_by_key(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::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, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::Config::find_by_key(&conn, key)
- .await
- .map_err(|error| report!(errors::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, errors::StorageError> {
- let find_config_by_key_from_db = || async {
- let conn = connection::pg_connection_write(self).await?;
- storage::Config::find_by_key(&conn, key)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
- cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).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>,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let find_else_unwrap_or = || async {
- let conn = connection::pg_connection_write(self).await?;
- match storage::Config::find_by_key(&conn, key)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- {
- Ok(a) => Ok(a),
- 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)
- } else {
- Err(err)
- }
- }
- }
- };
-
- cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await
- }
-
- #[instrument(skip_all)]
- async fn delete_config_by_key(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- let deleted = storage::Config::delete_by_key(&conn, key)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- cache::redact_from_redis_and_publish(
- self.get_cache_store().as_ref(),
- [CacheKind::Config((&deleted.key).into())],
- )
- .await?;
-
- Ok(deleted)
- }
-}
-
-#[async_trait::async_trait]
-impl ConfigInterface for MockDb {
- #[instrument(skip_all)]
- async fn insert_config(
- &self,
- config: storage::ConfigNew,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let mut configs = self.configs.lock().await;
-
- let config_new = storage::Config {
- key: config.key,
- config: config.config,
- };
- configs.push(config_new.clone());
- Ok(config_new)
- }
-
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- self.update_config_by_key(key, config_update).await
- }
-
- async fn update_config_by_key(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let result = self
- .configs
- .lock()
- .await
- .iter_mut()
- .find(|c| c.key == key)
- .ok_or_else(|| {
- errors::StorageError::ValueNotFound("cannot find config to update".to_string())
- .into()
- })
- .map(|c| {
- let config_updated =
- ConfigUpdateInternal::from(config_update).create_config(c.clone());
- *c = config_updated.clone();
- config_updated
- });
-
- result
- }
-
- async fn delete_config_by_key(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let mut configs = self.configs.lock().await;
- let result = configs
- .iter()
- .position(|c| c.key == key)
- .map(|index| configs.remove(index))
- .ok_or_else(|| {
- errors::StorageError::ValueNotFound("cannot find config to delete".to_string())
- .into()
- });
-
- result
- }
-
- async fn find_config_by_key(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- let configs = self.configs.lock().await;
- let config = configs.iter().find(|c| c.key == key).cloned();
-
- config.ok_or_else(|| {
- errors::StorageError::ValueNotFound("cannot find config".to_string()).into()
- })
- }
-
- async fn find_config_by_key_unwrap_or(
- &self,
- key: &str,
- _default_config: Option<String>,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- self.find_config_by_key(key).await
- }
-
- async fn find_config_by_key_from_db(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- self.find_config_by_key(key).await
- }
-}
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index c80e9a24f9..10c1b8ddb2 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -862,10 +862,7 @@ mod tests {
use crate::{
core::webhooks as webhooks_core,
- db::{
- events::EventInterface, merchant_key_store::MerchantKeyStoreInterface,
- MasterKeyInterface, MockDb,
- },
+ db::{events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MockDb},
routes::{
self,
app::{settings::Settings, StorageImpl},
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 08e7b18678..22c3d1022a 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -5,7 +5,7 @@ use common_enums::enums::MerchantStorageScheme;
use common_utils::{
errors::CustomResult,
id_type,
- types::{keymanager::KeyManagerState, user::ThemeLineage},
+ types::{keymanager::KeyManagerState, user::ThemeLineage, TenantConfig},
};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
@@ -42,7 +42,7 @@ use scheduler::{
SchedulerInterface,
};
use serde::Serialize;
-use storage_impl::{config::TenantConfig, redis::kv_store::RedisConnInterface};
+use storage_impl::redis::kv_store::RedisConnInterface;
use time::PrimitiveDateTime;
use super::{
@@ -318,6 +318,7 @@ impl CardsInfoInterface for KafkaStore {
#[async_trait::async_trait]
impl ConfigInterface for KafkaStore {
+ type Error = errors::StorageError;
async fn insert_config(
&self,
config: storage::ConfigNew,
@@ -1060,6 +1061,7 @@ impl PaymentLinkInterface for KafkaStore {
#[async_trait::async_trait]
impl MerchantAccountInterface for KafkaStore {
+ type Error = errors::StorageError;
async fn insert_merchant(
&self,
state: &KeyManagerState,
@@ -1237,6 +1239,7 @@ impl FileMetadataInterface for KafkaStore {
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for KafkaStore {
+ type Error = errors::StorageError;
async fn update_multiple_merchant_connector_accounts(
&self,
merchant_connector_accounts: Vec<(
@@ -2948,6 +2951,7 @@ impl RefundInterface for KafkaStore {
#[async_trait::async_trait]
impl MerchantKeyStoreInterface for KafkaStore {
+ type Error = errors::StorageError;
async fn insert_merchant_key_store(
&self,
state: &KeyManagerState,
@@ -3005,6 +3009,7 @@ impl MerchantKeyStoreInterface for KafkaStore {
#[async_trait::async_trait]
impl ProfileInterface for KafkaStore {
+ type Error = errors::StorageError;
async fn insert_business_profile(
&self,
key_manager_state: &KeyManagerState,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 47851ae263..0611d063d3 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -1,823 +1 @@
-#[cfg(feature = "olap")]
-use std::collections::HashMap;
-
-use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};
-use diesel_models::MerchantAccountUpdateInternal;
-use error_stack::{report, ResultExt};
-use router_env::{instrument, tracing};
-#[cfg(feature = "accounts_cache")]
-use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE};
-
-use super::{MasterKeyInterface, MockDb, Store};
-use crate::{
- connection,
- core::errors::{self, CustomResult},
- db::merchant_key_store::MerchantKeyStoreInterface,
- types::{
- domain::{
- self,
- behaviour::{Conversion, ReverseConversion},
- },
- storage,
- },
-};
-
-#[async_trait::async_trait]
-pub trait MerchantAccountInterface
-where
- domain::MerchantAccount:
- Conversion<DstType = storage::MerchantAccount, NewDstType = storage::MerchantAccountNew>,
-{
- async fn insert_merchant(
- &self,
- state: &KeyManagerState,
- merchant_account: domain::MerchantAccount,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
-
- async fn find_merchant_account_by_merchant_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
-
- async fn update_all_merchant_account(
- &self,
- merchant_account: storage::MerchantAccountUpdate,
- ) -> CustomResult<usize, errors::StorageError>;
-
- async fn update_merchant(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantAccount,
- merchant_account: storage::MerchantAccountUpdate,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
-
- async fn update_specific_fields_in_merchant(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_account: storage::MerchantAccountUpdate,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
-
- async fn find_merchant_account_by_publishable_key(
- &self,
- state: &KeyManagerState,
- publishable_key: &str,
- ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError>;
-
- #[cfg(feature = "olap")]
- async fn list_merchant_accounts_by_organization_id(
- &self,
- state: &KeyManagerState,
- organization_id: &common_utils::id_type::OrganizationId,
- ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>;
-
- async fn delete_merchant_account_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError>;
-
- #[cfg(feature = "olap")]
- async fn list_multiple_merchant_accounts(
- &self,
- state: &KeyManagerState,
- merchant_ids: Vec<common_utils::id_type::MerchantId>,
- ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>;
-
- #[cfg(feature = "olap")]
- async fn list_merchant_and_org_ids(
- &self,
- state: &KeyManagerState,
- limit: u32,
- offset: Option<u32>,
- ) -> CustomResult<
- Vec<(
- common_utils::id_type::MerchantId,
- common_utils::id_type::OrganizationId,
- )>,
- errors::StorageError,
- >;
-}
-
-#[async_trait::async_trait]
-impl MerchantAccountInterface for Store {
- #[instrument(skip_all)]
- async fn insert_merchant(
- &self,
- state: &KeyManagerState,
- merchant_account: domain::MerchantAccount,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- merchant_account
- .construct_new()
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .insert(&conn)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn find_merchant_account_by_merchant_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let fetch_func = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- fetch_func()
- .await?
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_id.to_owned().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- cache::get_or_populate_in_memory(
- self,
- merchant_id.get_string_repr(),
- fetch_func,
- &ACCOUNTS_CACHE,
- )
- .await?
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
- }
-
- #[instrument(skip_all)]
- async fn update_merchant(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantAccount,
- merchant_account: storage::MerchantAccountUpdate,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
-
- let updated_merchant_account = Conversion::convert(this)
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .update(&conn, merchant_account.into())
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- #[cfg(feature = "accounts_cache")]
- {
- publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?;
- }
- updated_merchant_account
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn update_specific_fields_in_merchant(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_account: storage::MerchantAccountUpdate,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields(
- &conn,
- merchant_id,
- merchant_account.into(),
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- #[cfg(feature = "accounts_cache")]
- {
- publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?;
- }
- updated_merchant_account
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn find_merchant_account_by_publishable_key(
- &self,
- state: &KeyManagerState,
- publishable_key: &str,
- ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError>
- {
- let fetch_by_pub_key_func = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- let merchant_account;
- #[cfg(not(feature = "accounts_cache"))]
- {
- merchant_account = fetch_by_pub_key_func().await?;
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- merchant_account = cache::get_or_populate_in_memory(
- self,
- publishable_key,
- fetch_by_pub_key_func,
- &ACCOUNTS_CACHE,
- )
- .await?;
- }
- let key_store = self
- .get_merchant_key_store_by_merchant_id(
- state,
- merchant_account.get_id(),
- &self.get_master_key().to_vec().into(),
- )
- .await?;
- let domain_merchant_account = merchant_account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?;
- Ok((domain_merchant_account, key_store))
- }
-
- #[cfg(feature = "olap")]
- #[instrument(skip_all)]
- async fn list_merchant_accounts_by_organization_id(
- &self,
- state: &KeyManagerState,
- organization_id: &common_utils::id_type::OrganizationId,
- ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
- use futures::future::try_join_all;
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- let encrypted_merchant_accounts =
- storage::MerchantAccount::list_by_organization_id(&conn, organization_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- let db_master_key = self.get_master_key().to_vec().into();
-
- let merchant_key_stores =
- try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| {
- self.get_merchant_key_store_by_merchant_id(
- state,
- merchant_account.get_id(),
- &db_master_key,
- )
- }))
- .await?;
-
- let merchant_accounts = try_join_all(
- encrypted_merchant_accounts
- .into_iter()
- .zip(merchant_key_stores.iter())
- .map(|(merchant_account, key_store)| async {
- merchant_account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }),
- )
- .await?;
-
- Ok(merchant_accounts)
- }
-
- #[instrument(skip_all)]
- async fn delete_merchant_account_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
-
- let is_deleted_func = || async {
- storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- let is_deleted;
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- is_deleted = is_deleted_func().await?;
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- let merchant_account =
- storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- is_deleted = is_deleted_func().await?;
-
- publish_and_redact_merchant_account_cache(self, &merchant_account).await?;
- }
-
- Ok(is_deleted)
- }
-
- #[cfg(feature = "olap")]
- #[instrument(skip_all)]
- async fn list_multiple_merchant_accounts(
- &self,
- state: &KeyManagerState,
- merchant_ids: Vec<common_utils::id_type::MerchantId>,
- ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- let encrypted_merchant_accounts =
- storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- let db_master_key = self.get_master_key().to_vec().into();
-
- let merchant_key_stores = self
- .list_multiple_key_stores(
- state,
- encrypted_merchant_accounts
- .iter()
- .map(|merchant_account| merchant_account.get_id())
- .cloned()
- .collect(),
- &db_master_key,
- )
- .await?;
-
- let key_stores_by_id: HashMap<_, _> = merchant_key_stores
- .iter()
- .map(|key_store| (key_store.merchant_id.to_owned(), key_store))
- .collect();
-
- let merchant_accounts =
- futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map(
- |merchant_account| async {
- let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or(
- errors::StorageError::ValueNotFound(format!(
- "merchant_key_store with merchant_id = {:?}",
- merchant_account.get_id()
- )),
- )?;
- merchant_account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- },
- ))
- .await?;
-
- Ok(merchant_accounts)
- }
-
- #[cfg(feature = "olap")]
- #[instrument(skip_all)]
- async fn list_merchant_and_org_ids(
- &self,
- _state: &KeyManagerState,
- limit: u32,
- offset: Option<u32>,
- ) -> CustomResult<
- Vec<(
- common_utils::id_type::MerchantId,
- common_utils::id_type::OrganizationId,
- )>,
- errors::StorageError,
- > {
- let conn = connection::pg_accounts_connection_read(self).await?;
- let encrypted_merchant_accounts =
- storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- let merchant_and_org_ids = encrypted_merchant_accounts
- .into_iter()
- .map(|merchant_account| {
- let merchant_id = merchant_account.get_id().clone();
- let org_id = merchant_account.organization_id;
- (merchant_id, org_id)
- })
- .collect();
- Ok(merchant_and_org_ids)
- }
-
- async fn update_all_merchant_account(
- &self,
- merchant_account: storage::MerchantAccountUpdate,
- ) -> CustomResult<usize, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- let db_func = || async {
- storage::MerchantAccount::update_all_merchant_accounts(
- &conn,
- MerchantAccountUpdateInternal::from(merchant_account),
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- let total;
- #[cfg(not(feature = "accounts_cache"))]
- {
- let ma = db_func().await?;
- total = ma.len();
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- let ma = db_func().await?;
- publish_and_redact_all_merchant_account_cache(self, &ma).await?;
- total = ma.len();
- }
-
- Ok(total)
- }
-}
-
-#[async_trait::async_trait]
-impl MerchantAccountInterface for MockDb {
- #[allow(clippy::panic)]
- async fn insert_merchant(
- &self,
- state: &KeyManagerState,
- merchant_account: domain::MerchantAccount,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let mut accounts = self.merchant_accounts.lock().await;
- let account = Conversion::convert(merchant_account)
- .await
- .change_context(errors::StorageError::EncryptionError)?;
- accounts.push(account.clone());
-
- account
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[allow(clippy::panic)]
- async fn find_merchant_account_by_merchant_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let accounts = self.merchant_accounts.lock().await;
- accounts
- .iter()
- .find(|account| account.get_id() == merchant_id)
- .cloned()
- .ok_or(errors::StorageError::ValueNotFound(format!(
- "Merchant ID: {merchant_id:?} not found",
- )))?
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- async fn update_merchant(
- &self,
- state: &KeyManagerState,
- merchant_account: domain::MerchantAccount,
- merchant_account_update: storage::MerchantAccountUpdate,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let merchant_id = merchant_account.get_id().to_owned();
- let mut accounts = self.merchant_accounts.lock().await;
- accounts
- .iter_mut()
- .find(|account| account.get_id() == merchant_account.get_id())
- .async_map(|account| async {
- let update = MerchantAccountUpdateInternal::from(merchant_account_update)
- .apply_changeset(
- Conversion::convert(merchant_account)
- .await
- .change_context(errors::StorageError::EncryptionError)?,
- );
- *account = update.clone();
- update
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "Merchant ID: {merchant_id:?} not found",
- ))
- .into(),
- )
- }
-
- async fn update_specific_fields_in_merchant(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_account_update: storage::MerchantAccountUpdate,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
- let mut accounts = self.merchant_accounts.lock().await;
- accounts
- .iter_mut()
- .find(|account| account.get_id() == merchant_id)
- .async_map(|account| async {
- let update = MerchantAccountUpdateInternal::from(merchant_account_update)
- .apply_changeset(account.clone());
- *account = update.clone();
- update
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "Merchant ID: {merchant_id:?} not found",
- ))
- .into(),
- )
- }
-
- async fn find_merchant_account_by_publishable_key(
- &self,
- state: &KeyManagerState,
- publishable_key: &str,
- ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError>
- {
- let accounts = self.merchant_accounts.lock().await;
- let account = accounts
- .iter()
- .find(|account| {
- account
- .publishable_key
- .as_ref()
- .is_some_and(|key| key == publishable_key)
- })
- .ok_or(errors::StorageError::ValueNotFound(format!(
- "Publishable Key: {publishable_key} not found",
- )))?;
- let key_store = self
- .get_merchant_key_store_by_merchant_id(
- state,
- account.get_id(),
- &self.get_master_key().to_vec().into(),
- )
- .await?;
- let merchant_account = account
- .clone()
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?;
- Ok((merchant_account, key_store))
- }
-
- async fn update_all_merchant_account(
- &self,
- merchant_account_update: storage::MerchantAccountUpdate,
- ) -> CustomResult<usize, errors::StorageError> {
- let mut accounts = self.merchant_accounts.lock().await;
- Ok(accounts.iter_mut().fold(0, |acc, account| {
- let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone())
- .apply_changeset(account.clone());
- *account = update;
- acc + 1
- }))
- }
-
- async fn delete_merchant_account_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError> {
- let mut accounts = self.merchant_accounts.lock().await;
- accounts.retain(|x| x.get_id() != merchant_id);
- Ok(true)
- }
-
- #[cfg(feature = "olap")]
- async fn list_merchant_accounts_by_organization_id(
- &self,
- state: &KeyManagerState,
- organization_id: &common_utils::id_type::OrganizationId,
- ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
- let accounts = self.merchant_accounts.lock().await;
- let futures = accounts
- .iter()
- .filter(|account| account.organization_id == *organization_id)
- .map(|account| async {
- let key_store = self
- .get_merchant_key_store_by_merchant_id(
- state,
- account.get_id(),
- &self.get_master_key().to_vec().into(),
- )
- .await;
- match key_store {
- Ok(key) => account
- .clone()
- .convert(state, key.key.get_inner(), key.merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError),
- Err(err) => Err(err),
- }
- });
- futures::future::join_all(futures)
- .await
- .into_iter()
- .collect()
- }
-
- #[cfg(feature = "olap")]
- async fn list_multiple_merchant_accounts(
- &self,
- state: &KeyManagerState,
- merchant_ids: Vec<common_utils::id_type::MerchantId>,
- ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
- let accounts = self.merchant_accounts.lock().await;
- let futures = accounts
- .iter()
- .filter(|account| merchant_ids.contains(account.get_id()))
- .map(|account| async {
- let key_store = self
- .get_merchant_key_store_by_merchant_id(
- state,
- account.get_id(),
- &self.get_master_key().to_vec().into(),
- )
- .await;
- match key_store {
- Ok(key) => account
- .clone()
- .convert(state, key.key.get_inner(), key.merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError),
- Err(err) => Err(err),
- }
- });
- futures::future::join_all(futures)
- .await
- .into_iter()
- .collect()
- }
-
- #[cfg(feature = "olap")]
- async fn list_merchant_and_org_ids(
- &self,
- _state: &KeyManagerState,
- limit: u32,
- offset: Option<u32>,
- ) -> CustomResult<
- Vec<(
- common_utils::id_type::MerchantId,
- common_utils::id_type::OrganizationId,
- )>,
- errors::StorageError,
- > {
- let accounts = self.merchant_accounts.lock().await;
- let limit = limit.try_into().unwrap_or(accounts.len());
- let offset = offset.unwrap_or(0).try_into().unwrap_or(0);
-
- let merchant_and_org_ids = accounts
- .iter()
- .skip(offset)
- .take(limit)
- .map(|account| (account.get_id().clone(), account.organization_id.clone()))
- .collect::<Vec<_>>();
-
- Ok(merchant_and_org_ids)
- }
-}
-
-#[cfg(feature = "accounts_cache")]
-async fn publish_and_redact_merchant_account_cache(
- store: &dyn super::StorageInterface,
- merchant_account: &storage::MerchantAccount,
-) -> CustomResult<(), errors::StorageError> {
- let publishable_key = merchant_account
- .publishable_key
- .as_ref()
- .map(|publishable_key| CacheKind::Accounts(publishable_key.into()));
-
- #[cfg(feature = "v1")]
- let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| {
- CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- merchant_account.get_id().get_string_repr(),
- profile_id.get_string_repr(),
- )
- .into(),
- )
- });
-
- // TODO: we will not have default profile in v2
- #[cfg(feature = "v2")]
- let cgraph_key = None;
-
- let mut cache_keys = vec![CacheKind::Accounts(
- merchant_account.get_id().get_string_repr().into(),
- )];
-
- cache_keys.extend(publishable_key.into_iter());
- cache_keys.extend(cgraph_key.into_iter());
-
- cache::redact_from_redis_and_publish(store.get_cache_store().as_ref(), cache_keys).await?;
- Ok(())
-}
-
-#[cfg(feature = "accounts_cache")]
-async fn publish_and_redact_all_merchant_account_cache(
- store: &dyn super::StorageInterface,
- merchant_accounts: &[storage::MerchantAccount],
-) -> CustomResult<(), errors::StorageError> {
- let merchant_ids = merchant_accounts
- .iter()
- .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string());
- let publishable_keys = merchant_accounts
- .iter()
- .filter_map(|m| m.publishable_key.clone());
-
- let cache_keys: Vec<CacheKind<'_>> = merchant_ids
- .chain(publishable_keys)
- .map(|s| CacheKind::Accounts(s.into()))
- .collect();
-
- cache::redact_from_redis_and_publish(store.get_cache_store().as_ref(), cache_keys).await?;
- Ok(())
-}
+pub use hyperswitch_domain_models::merchant_account::{self, MerchantAccountInterface};
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index b9618e2c63..8495c344bb 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -1,27 +1,13 @@
-use async_bb8_diesel::AsyncConnection;
-use common_utils::{
- encryption::Encryption,
- ext_traits::{AsyncExt, ByteSliceExt, Encode},
- types::keymanager::KeyManagerState,
-};
-use error_stack::{report, ResultExt};
+use common_utils::ext_traits::{ByteSliceExt, Encode};
+use error_stack::ResultExt;
+pub use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountInterface;
use router_env::{instrument, tracing};
-#[cfg(feature = "accounts_cache")]
-use storage_impl::redis::cache;
use storage_impl::redis::kv_store::RedisConnInterface;
use super::{MockDb, Store};
use crate::{
- connection,
core::errors::{self, CustomResult},
- types::{
- self,
- domain::{
- self,
- behaviour::{Conversion, ReverseConversion},
- },
- storage,
- },
+ types,
};
#[async_trait::async_trait]
@@ -114,1411 +100,6 @@ impl ConnectorAccessToken for MockDb {
}
}
-#[async_trait::async_trait]
-pub trait MerchantConnectorAccountInterface
-where
- domain::MerchantConnectorAccount: Conversion<
- DstType = storage::MerchantConnectorAccount,
- NewDstType = storage::MerchantConnectorAccountNew,
- >,
-{
- #[cfg(feature = "v1")]
- async fn find_merchant_connector_account_by_merchant_id_connector_label(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- connector_label: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
-
- #[cfg(feature = "v1")]
- async fn find_merchant_connector_account_by_profile_id_connector_name(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- connector_name: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
-
- #[cfg(feature = "v1")]
- async fn find_merchant_connector_account_by_merchant_id_connector_name(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- connector_name: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>;
-
- async fn insert_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- t: domain::MerchantConnectorAccount,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
-
- #[cfg(feature = "v1")]
- async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
-
- #[cfg(feature = "v2")]
- async fn find_merchant_connector_account_by_id(
- &self,
- state: &KeyManagerState,
- id: &common_utils::id_type::MerchantConnectorAccountId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
-
- async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- get_disabled: bool,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError>;
-
- #[cfg(all(feature = "olap", feature = "v2"))]
- async fn list_connector_account_by_profile_id(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>;
-
- async fn list_enabled_connector_accounts_by_profile_id(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- key_store: &domain::MerchantKeyStore,
- connector_type: common_enums::ConnectorType,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>;
-
- async fn update_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantConnectorAccount,
- merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
-
- async fn update_multiple_merchant_connector_accounts(
- &self,
- this: Vec<(
- domain::MerchantConnectorAccount,
- storage::MerchantConnectorAccountUpdateInternal,
- )>,
- ) -> CustomResult<(), errors::StorageError>;
-
- #[cfg(feature = "v1")]
- async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- ) -> CustomResult<bool, errors::StorageError>;
-
- #[cfg(feature = "v2")]
- async fn delete_merchant_connector_account_by_id(
- &self,
- id: &common_utils::id_type::MerchantConnectorAccountId,
- ) -> CustomResult<bool, errors::StorageError>;
-}
-
-#[async_trait::async_trait]
-impl MerchantConnectorAccountInterface for Store {
- #[cfg(feature = "v1")]
- #[instrument(skip_all)]
- async fn find_merchant_connector_account_by_merchant_id_connector_label(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- connector_label: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let find_call = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantConnectorAccount::find_by_merchant_id_connector(
- &conn,
- merchant_id,
- connector_label,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- find_call()
- .await?
- .convert(state, key_store.key.get_inner(), merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DeserializationFailed)
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- cache::get_or_populate_in_memory(
- self,
- &format!("{}_{}", merchant_id.get_string_repr(), connector_label),
- find_call,
- &cache::ACCOUNTS_CACHE,
- )
- .await
- .async_and_then(|item| async {
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- }
- }
-
- #[cfg(feature = "v1")]
- #[instrument(skip_all)]
- async fn find_merchant_connector_account_by_profile_id_connector_name(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- connector_name: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let find_call = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantConnectorAccount::find_by_profile_id_connector_name(
- &conn,
- profile_id,
- connector_name,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- find_call()
- .await?
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DeserializationFailed)
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- cache::get_or_populate_in_memory(
- self,
- &format!("{}_{}", profile_id.get_string_repr(), connector_name),
- find_call,
- &cache::ACCOUNTS_CACHE,
- )
- .await
- .async_and_then(|item| async {
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- }
- }
-
- #[cfg(feature = "v1")]
- #[instrument(skip_all)]
- async fn find_merchant_connector_account_by_merchant_id_connector_name(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- connector_name: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantConnectorAccount::find_by_merchant_id_connector_name(
- &conn,
- merchant_id,
- connector_name,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|items| async {
- let mut output = Vec::with_capacity(items.len());
- for item in items.into_iter() {
- output.push(
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(output)
- })
- .await
- }
-
- #[instrument(skip_all)]
- #[cfg(feature = "v1")]
- async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let find_call = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(
- &conn,
- merchant_id,
- merchant_connector_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- find_call()
- .await?
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- cache::get_or_populate_in_memory(
- self,
- &format!(
- "{}_{}",
- merchant_id.get_string_repr(),
- merchant_connector_id.get_string_repr()
- ),
- find_call,
- &cache::ACCOUNTS_CACHE,
- )
- .await?
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
- }
-
- #[instrument(skip_all)]
- #[cfg(feature = "v2")]
- async fn find_merchant_connector_account_by_id(
- &self,
- state: &KeyManagerState,
- id: &common_utils::id_type::MerchantConnectorAccountId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let find_call = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantConnectorAccount::find_by_id(&conn, id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- find_call()
- .await?
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- cache::get_or_populate_in_memory(
- self,
- id.get_string_repr(),
- find_call,
- &cache::ACCOUNTS_CACHE,
- )
- .await?
- .convert(
- state,
- key_store.key.get_inner(),
- common_utils::types::keymanager::Identifier::Merchant(
- key_store.merchant_id.clone(),
- ),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
- }
-
- #[instrument(skip_all)]
- async fn insert_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- t: domain::MerchantConnectorAccount,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- t.construct_new()
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .insert(&conn)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|item| async {
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- }
-
- async fn list_enabled_connector_accounts_by_profile_id(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- key_store: &domain::MerchantKeyStore,
- connector_type: common_enums::ConnectorType,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- storage::MerchantConnectorAccount::list_enabled_by_profile_id(
- &conn,
- profile_id,
- connector_type,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|items| async {
- let mut output = Vec::with_capacity(items.len());
- for item in items.into_iter() {
- output.push(
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(output)
- })
- .await
- }
-
- #[instrument(skip_all)]
- async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- get_disabled: bool,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- let merchant_connector_account_vec =
- storage::MerchantConnectorAccount::find_by_merchant_id(
- &conn,
- merchant_id,
- get_disabled,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|items| async {
- let mut output = Vec::with_capacity(items.len());
- for item in items.into_iter() {
- output.push(
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(output)
- })
- .await?;
- Ok(domain::MerchantConnectorAccounts::new(
- merchant_connector_account_vec,
- ))
- }
-
- #[instrument(skip_all)]
- #[cfg(all(feature = "olap", feature = "v2"))]
- async fn list_connector_account_by_profile_id(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|items| async {
- let mut output = Vec::with_capacity(items.len());
- for item in items.into_iter() {
- output.push(
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(output)
- })
- .await
- }
-
- #[instrument(skip_all)]
- async fn update_multiple_merchant_connector_accounts(
- &self,
- merchant_connector_accounts: Vec<(
- domain::MerchantConnectorAccount,
- storage::MerchantConnectorAccountUpdateInternal,
- )>,
- ) -> CustomResult<(), errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
-
- async fn update_call(
- connection: &diesel_models::PgPooledConn,
- (merchant_connector_account, mca_update): (
- domain::MerchantConnectorAccount,
- storage::MerchantConnectorAccountUpdateInternal,
- ),
- ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> {
- Conversion::convert(merchant_connector_account)
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .update(connection, mca_update)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
- Ok(())
- }
-
- conn.transaction_async(|connection_pool| async move {
- for (merchant_connector_account, update_merchant_connector_account) in
- merchant_connector_accounts
- {
- #[cfg(feature = "v1")]
- let _connector_name = merchant_connector_account.connector_name.clone();
-
- #[cfg(feature = "v2")]
- let _connector_name = merchant_connector_account.connector_name.to_string();
-
- let _profile_id = merchant_connector_account.profile_id.clone();
-
- let _merchant_id = merchant_connector_account.merchant_id.clone();
- let _merchant_connector_id = merchant_connector_account.get_id().clone();
-
- let update = update_call(
- &connection_pool,
- (
- merchant_connector_account,
- update_merchant_connector_account,
- ),
- );
-
- #[cfg(feature = "accounts_cache")]
- // Redact all caches as any of might be used because of backwards compatibility
- Box::pin(cache::publish_and_redact_multiple(
- self,
- [
- cache::CacheKind::Accounts(
- format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
- ),
- cache::CacheKind::Accounts(
- format!(
- "{}_{}",
- _merchant_id.get_string_repr(),
- _merchant_connector_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- _merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- ],
- || update,
- ))
- .await
- .map_err(|error| {
- // Returning `DatabaseConnectionError` after logging the actual error because
- // -> it is not possible to get the underlying from `error_stack::Report<C>`
- // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
- // because of Rust's orphan rules
- router_env::logger::error!(
- ?error,
- "DB transaction for updating multiple merchant connector account failed"
- );
- errors::StorageError::DatabaseConnectionError
- })?;
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- update.await.map_err(|error| {
- // Returning `DatabaseConnectionError` after logging the actual error because
- // -> it is not possible to get the underlying from `error_stack::Report<C>`
- // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
- // because of Rust's orphan rules
- router_env::logger::error!(
- ?error,
- "DB transaction for updating multiple merchant connector account failed"
- );
- errors::StorageError::DatabaseConnectionError
- })?;
- }
- }
- Ok::<_, errors::StorageError>(())
- })
- .await?;
- Ok(())
- }
-
- #[instrument(skip_all)]
- #[cfg(feature = "v1")]
- async fn update_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantConnectorAccount,
- merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let _connector_name = this.connector_name.clone();
- let _profile_id = this.profile_id.clone();
-
- let _merchant_id = this.merchant_id.clone();
- let _merchant_connector_id = this.merchant_connector_id.clone();
-
- let update_call = || async {
- let conn = connection::pg_accounts_connection_write(self).await?;
- Conversion::convert(this)
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .update(&conn, merchant_connector_account)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|item| async {
- item.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- };
-
- #[cfg(feature = "accounts_cache")]
- {
- // Redact all caches as any of might be used because of backwards compatibility
- cache::publish_and_redact_multiple(
- self,
- [
- cache::CacheKind::Accounts(
- format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
- ),
- cache::CacheKind::Accounts(
- format!(
- "{}_{}",
- _merchant_id.get_string_repr(),
- _merchant_connector_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- _merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::PmFiltersCGraph(
- format!(
- "pm_filters_cgraph_{}_{}",
- _merchant_id.get_string_repr(),
- _profile_id.get_string_repr(),
- )
- .into(),
- ),
- ],
- update_call,
- )
- .await
- }
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- update_call().await
- }
- }
-
- #[instrument(skip_all)]
- #[cfg(feature = "v2")]
- async fn update_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantConnectorAccount,
- merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let _connector_name = this.connector_name;
- let _profile_id = this.profile_id.clone();
-
- let _merchant_id = this.merchant_id.clone();
- let _merchant_connector_id = this.get_id().clone();
-
- let update_call = || async {
- let conn = connection::pg_accounts_connection_write(self).await?;
- Conversion::convert(this)
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .update(&conn, merchant_connector_account)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|item| async {
- item.convert(
- state,
- key_store.key.get_inner(),
- common_utils::types::keymanager::Identifier::Merchant(
- key_store.merchant_id.clone(),
- ),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- };
-
- #[cfg(feature = "accounts_cache")]
- {
- // Redact all caches as any of might be used because of backwards compatibility
- cache::publish_and_redact_multiple(
- self,
- [
- cache::CacheKind::Accounts(
- format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
- ),
- cache::CacheKind::Accounts(
- _merchant_connector_id.get_string_repr().to_string().into(),
- ),
- cache::CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- _merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::PmFiltersCGraph(
- format!(
- "pm_filters_cgraph_{}_{}",
- _merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- ],
- update_call,
- )
- .await
- }
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- update_call().await
- }
- }
-
- #[instrument(skip_all)]
- #[cfg(feature = "v1")]
- async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- ) -> CustomResult<bool, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- let delete_call = || async {
- storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id(
- &conn,
- merchant_id,
- merchant_connector_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(feature = "accounts_cache")]
- {
- // We need to fetch mca here because the key that's saved in cache in
- // {merchant_id}_{connector_label}.
- // Used function from storage model to reuse the connection that made here instead of
- // creating new.
-
- let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(
- &conn,
- merchant_id,
- merchant_connector_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- let _profile_id = mca.profile_id.ok_or(errors::StorageError::ValueNotFound(
- "profile_id".to_string(),
- ))?;
-
- cache::publish_and_redact_multiple(
- self,
- [
- cache::CacheKind::Accounts(
- format!(
- "{}_{}",
- mca.merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- mca.merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::PmFiltersCGraph(
- format!(
- "pm_filters_cgraph_{}_{}",
- mca.merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- ],
- delete_call,
- )
- .await
- }
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- delete_call().await
- }
- }
-
- #[instrument(skip_all)]
- #[cfg(feature = "v2")]
- async fn delete_merchant_connector_account_by_id(
- &self,
- id: &common_utils::id_type::MerchantConnectorAccountId,
- ) -> CustomResult<bool, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- let delete_call = || async {
- storage::MerchantConnectorAccount::delete_by_id(&conn, id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(feature = "accounts_cache")]
- {
- // We need to fetch mca here because the key that's saved in cache in
- // {merchant_id}_{connector_label}.
- // Used function from storage model to reuse the connection that made here instead of
- // creating new.
-
- let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
-
- let _profile_id = mca.profile_id;
-
- cache::publish_and_redact_multiple(
- self,
- [
- cache::CacheKind::Accounts(
- format!(
- "{}_{}",
- mca.merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- mca.merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::PmFiltersCGraph(
- format!(
- "pm_filters_cgraph_{}_{}",
- mca.merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
- ),
- ],
- delete_call,
- )
- .await
- }
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- delete_call().await
- }
- }
-}
-
-#[async_trait::async_trait]
-impl MerchantConnectorAccountInterface for MockDb {
- async fn update_multiple_merchant_connector_accounts(
- &self,
- _merchant_connector_accounts: Vec<(
- domain::MerchantConnectorAccount,
- storage::MerchantConnectorAccountUpdateInternal,
- )>,
- ) -> CustomResult<(), errors::StorageError> {
- // No need to implement this function for `MockDb` as this function will be removed after the
- // apple pay certificate migration
- Err(errors::StorageError::MockDbError)?
- }
- #[cfg(feature = "v1")]
- async fn find_merchant_connector_account_by_merchant_id_connector_label(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- connector: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- match self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .find(|account| {
- account.merchant_id == *merchant_id
- && account.connector_label == Some(connector.to_string())
- })
- .cloned()
- .async_map(|account| async {
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- {
- Some(result) => result,
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account".to_string(),
- )
- .into())
- }
- }
- }
-
- async fn list_enabled_connector_accounts_by_profile_id(
- &self,
- _state: &KeyManagerState,
- _profile_id: &common_utils::id_type::ProfileId,
- _key_store: &domain::MerchantKeyStore,
- _connector_type: common_enums::ConnectorType,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
- Err(errors::StorageError::MockDbError)?
- }
-
- #[cfg(feature = "v1")]
- async fn find_merchant_connector_account_by_merchant_id_connector_name(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- connector_name: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
- let accounts = self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .filter(|account| {
- account.merchant_id == *merchant_id && account.connector_name == connector_name
- })
- .cloned()
- .collect::<Vec<_>>();
- let mut output = Vec::with_capacity(accounts.len());
- for account in accounts.into_iter() {
- output.push(
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(output)
- }
-
- #[cfg(feature = "v1")]
- async fn find_merchant_connector_account_by_profile_id_connector_name(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- connector_name: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let maybe_mca = self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .find(|account| {
- account.profile_id.eq(&Some(profile_id.to_owned()))
- && account.connector_name == connector_name
- })
- .cloned();
-
- match maybe_mca {
- Some(mca) => mca
- .to_owned()
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError),
- None => Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account".to_string(),
- )
- .into()),
- }
- }
-
- #[cfg(feature = "v1")]
- async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- match self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .find(|account| {
- account.merchant_id == *merchant_id
- && account.merchant_connector_id == *merchant_connector_id
- })
- .cloned()
- .async_map(|account| async {
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- {
- Some(result) => result,
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account".to_string(),
- )
- .into())
- }
- }
- }
-
- #[cfg(feature = "v2")]
- async fn find_merchant_connector_account_by_id(
- &self,
- state: &KeyManagerState,
- id: &common_utils::id_type::MerchantConnectorAccountId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- match self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .find(|account| account.get_id() == *id)
- .cloned()
- .async_map(|account| async {
- account
- .convert(
- state,
- key_store.key.get_inner(),
- common_utils::types::keymanager::Identifier::Merchant(
- key_store.merchant_id.clone(),
- ),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- {
- Some(result) => result,
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account".to_string(),
- )
- .into())
- }
- }
- }
-
- #[cfg(feature = "v1")]
- async fn insert_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- t: domain::MerchantConnectorAccount,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let mut accounts = self.merchant_connector_accounts.lock().await;
- let account = storage::MerchantConnectorAccount {
- merchant_id: t.merchant_id,
- connector_name: t.connector_name,
- connector_account_details: t.connector_account_details.into(),
- test_mode: t.test_mode,
- disabled: t.disabled,
- merchant_connector_id: t.merchant_connector_id.clone(),
- id: Some(t.merchant_connector_id),
- payment_methods_enabled: t.payment_methods_enabled,
- metadata: t.metadata,
- frm_configs: None,
- frm_config: t.frm_configs,
- connector_type: t.connector_type,
- connector_label: t.connector_label,
- business_country: t.business_country,
- business_label: t.business_label,
- business_sub_label: t.business_sub_label,
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- connector_webhook_details: t.connector_webhook_details,
- profile_id: Some(t.profile_id),
- applepay_verified_domains: t.applepay_verified_domains,
- pm_auth_config: t.pm_auth_config,
- status: t.status,
- connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
- additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
- version: t.version,
- };
- accounts.push(account.clone());
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[cfg(feature = "v2")]
- async fn insert_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- t: domain::MerchantConnectorAccount,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let mut accounts = self.merchant_connector_accounts.lock().await;
- let account = storage::MerchantConnectorAccount {
- id: t.id,
- merchant_id: t.merchant_id,
- connector_name: t.connector_name,
- connector_account_details: t.connector_account_details.into(),
- disabled: t.disabled,
- payment_methods_enabled: t.payment_methods_enabled,
- metadata: t.metadata,
- frm_config: t.frm_configs,
- connector_type: t.connector_type,
- connector_label: t.connector_label,
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- connector_webhook_details: t.connector_webhook_details,
- profile_id: t.profile_id,
- applepay_verified_domains: t.applepay_verified_domains,
- pm_auth_config: t.pm_auth_config,
- status: t.status,
- connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
- additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
- version: t.version,
- feature_metadata: t.feature_metadata.map(From::from),
- };
- accounts.push(account.clone());
- account
- .convert(
- state,
- key_store.key.get_inner(),
- common_utils::types::keymanager::Identifier::Merchant(
- key_store.merchant_id.clone(),
- ),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- get_disabled: bool,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> {
- let accounts = self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .filter(|account: &&storage::MerchantConnectorAccount| {
- if get_disabled {
- account.merchant_id == *merchant_id
- } else {
- account.merchant_id == *merchant_id && account.disabled == Some(false)
- }
- })
- .cloned()
- .collect::<Vec<storage::MerchantConnectorAccount>>();
-
- let mut output = Vec::with_capacity(accounts.len());
- for account in accounts.into_iter() {
- output.push(
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(domain::MerchantConnectorAccounts::new(output))
- }
-
- #[cfg(all(feature = "olap", feature = "v2"))]
- async fn list_connector_account_by_profile_id(
- &self,
- state: &KeyManagerState,
- profile_id: &common_utils::id_type::ProfileId,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
- let accounts = self
- .merchant_connector_accounts
- .lock()
- .await
- .iter()
- .filter(|account: &&storage::MerchantConnectorAccount| {
- account.profile_id == *profile_id
- })
- .cloned()
- .collect::<Vec<storage::MerchantConnectorAccount>>();
-
- let mut output = Vec::with_capacity(accounts.len());
- for account in accounts.into_iter() {
- output.push(
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- )
- }
- Ok(output)
- }
-
- #[cfg(feature = "v1")]
- async fn update_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantConnectorAccount,
- merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let mca_update_res = self
- .merchant_connector_accounts
- .lock()
- .await
- .iter_mut()
- .find(|account| account.merchant_connector_id == this.merchant_connector_id)
- .map(|a| {
- let updated =
- merchant_connector_account.create_merchant_connector_account(a.clone());
- *a = updated.clone();
- updated
- })
- .async_map(|account| async {
- account
- .convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await;
-
- match mca_update_res {
- Some(result) => result,
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account to update".to_string(),
- )
- .into())
- }
- }
- }
-
- #[cfg(feature = "v2")]
- async fn update_merchant_connector_account(
- &self,
- state: &KeyManagerState,
- this: domain::MerchantConnectorAccount,
- merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- let mca_update_res = self
- .merchant_connector_accounts
- .lock()
- .await
- .iter_mut()
- .find(|account| account.get_id() == this.get_id())
- .map(|a| {
- let updated =
- merchant_connector_account.create_merchant_connector_account(a.clone());
- *a = updated.clone();
- updated
- })
- .async_map(|account| async {
- account
- .convert(
- state,
- key_store.key.get_inner(),
- common_utils::types::keymanager::Identifier::Merchant(
- key_store.merchant_id.clone(),
- ),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await;
-
- match mca_update_res {
- Some(result) => result,
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account to update".to_string(),
- )
- .into())
- }
- }
- }
-
- #[cfg(feature = "v1")]
- async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- ) -> CustomResult<bool, errors::StorageError> {
- let mut accounts = self.merchant_connector_accounts.lock().await;
- match accounts.iter().position(|account| {
- account.merchant_id == *merchant_id
- && account.merchant_connector_id == *merchant_connector_id
- }) {
- Some(index) => {
- accounts.remove(index);
- return Ok(true);
- }
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account to delete".to_string(),
- )
- .into())
- }
- }
- }
-
- #[cfg(feature = "v2")]
- async fn delete_merchant_connector_account_by_id(
- &self,
- id: &common_utils::id_type::MerchantConnectorAccountId,
- ) -> CustomResult<bool, errors::StorageError> {
- let mut accounts = self.merchant_connector_accounts.lock().await;
- match accounts.iter().position(|account| account.get_id() == *id) {
- Some(index) => {
- accounts.remove(index);
- return Ok(true);
- }
- None => {
- return Err(errors::StorageError::ValueNotFound(
- "cannot find merchant connector account to delete".to_string(),
- )
- .into())
- }
- }
- }
-}
-
#[cfg(feature = "accounts_cache")]
#[cfg(test)]
mod merchant_connector_account_cache_tests {
@@ -1542,7 +123,7 @@ mod merchant_connector_account_cache_tests {
core::errors,
db::{
merchant_connector_account::MerchantConnectorAccountInterface,
- merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb,
+ merchant_key_store::MerchantKeyStoreInterface, MockDb,
},
routes::{
self,
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index c1ce0f5fea..204544ac5f 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -1,320 +1,4 @@
-use common_utils::types::keymanager::KeyManagerState;
-use error_stack::{report, ResultExt};
-use masking::Secret;
-use router_env::{instrument, tracing};
-#[cfg(feature = "accounts_cache")]
-use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE};
-
-use crate::{
- connection,
- core::errors::{self, CustomResult},
- db::MockDb,
- services::Store,
- types::domain::{
- self,
- behaviour::{Conversion, ReverseConversion},
- },
-};
-
-#[async_trait::async_trait]
-pub trait MerchantKeyStoreInterface {
- async fn insert_merchant_key_store(
- &self,
- state: &KeyManagerState,
- merchant_key_store: domain::MerchantKeyStore,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>;
-
- async fn get_merchant_key_store_by_merchant_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>;
-
- async fn delete_merchant_key_store_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError>;
-
- #[cfg(feature = "olap")]
- async fn list_multiple_key_stores(
- &self,
- state: &KeyManagerState,
- merchant_ids: Vec<common_utils::id_type::MerchantId>,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>;
-
- async fn get_all_key_stores(
- &self,
- state: &KeyManagerState,
- key: &Secret<Vec<u8>>,
- from: u32,
- to: u32,
- ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>;
-}
-
-#[async_trait::async_trait]
-impl MerchantKeyStoreInterface for Store {
- #[instrument(skip_all)]
- async fn insert_merchant_key_store(
- &self,
- state: &KeyManagerState,
- merchant_key_store: domain::MerchantKeyStore,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
- let conn = connection::pg_accounts_connection_write(self).await?;
- let merchant_id = merchant_key_store.merchant_id.clone();
- merchant_key_store
- .construct_new()
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .insert(&conn)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(state, key, merchant_id.into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[instrument(skip_all)]
- async fn get_merchant_key_store_by_merchant_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
- let fetch_func = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id(
- &conn,
- merchant_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- fetch_func()
- .await?
- .convert(state, key, merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- let key_store_cache_key =
- format!("merchant_key_store_{}", merchant_id.get_string_repr());
- cache::get_or_populate_in_memory(
- self,
- &key_store_cache_key,
- fetch_func,
- &ACCOUNTS_CACHE,
- )
- .await?
- .convert(state, key, merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
- }
-
- #[instrument(skip_all)]
- async fn delete_merchant_key_store_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError> {
- let delete_func = || async {
- let conn = connection::pg_accounts_connection_write(self).await?;
- diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id(
- &conn,
- merchant_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- #[cfg(not(feature = "accounts_cache"))]
- {
- delete_func().await
- }
-
- #[cfg(feature = "accounts_cache")]
- {
- let key_store_cache_key =
- format!("merchant_key_store_{}", merchant_id.get_string_repr());
- cache::publish_and_redact(
- self,
- CacheKind::Accounts(key_store_cache_key.into()),
- delete_func,
- )
- .await
- }
- }
-
- #[cfg(feature = "olap")]
- #[instrument(skip_all)]
- async fn list_multiple_key_stores(
- &self,
- state: &KeyManagerState,
- merchant_ids: Vec<common_utils::id_type::MerchantId>,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
- let fetch_func = || async {
- let conn = connection::pg_accounts_connection_read(self).await?;
-
- diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores(
- &conn,
- merchant_ids,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
-
- futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async {
- let merchant_id = key_store.merchant_id.clone();
- key_store
- .convert(state, key, merchant_id.into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }))
- .await
- }
-
- async fn get_all_key_stores(
- &self,
- state: &KeyManagerState,
- key: &Secret<Vec<u8>>,
- from: u32,
- to: u32,
- ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
- let conn = connection::pg_accounts_connection_read(self).await?;
- let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(
- &conn, from, to,
- )
- .await
- .map_err(|err| report!(errors::StorageError::from(err)))?;
-
- futures::future::try_join_all(stores.into_iter().map(|key_store| async {
- let merchant_id = key_store.merchant_id.clone();
- key_store
- .convert(state, key, merchant_id.into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }))
- .await
- }
-}
-
-#[async_trait::async_trait]
-impl MerchantKeyStoreInterface for MockDb {
- async fn insert_merchant_key_store(
- &self,
- state: &KeyManagerState,
- merchant_key_store: domain::MerchantKeyStore,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
- let mut locked_merchant_key_store = self.merchant_key_store.lock().await;
-
- if locked_merchant_key_store
- .iter()
- .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id)
- {
- Err(errors::StorageError::DuplicateValue {
- entity: "merchant_key_store",
- key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()),
- })?;
- }
-
- let merchant_key = Conversion::convert(merchant_key_store)
- .await
- .change_context(errors::StorageError::MockDbError)?;
- locked_merchant_key_store.push(merchant_key.clone());
- let merchant_id = merchant_key.merchant_id.clone();
- merchant_key
- .convert(state, key, merchant_id.into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- async fn get_merchant_key_store_by_merchant_id(
- &self,
- state: &KeyManagerState,
- merchant_id: &common_utils::id_type::MerchantId,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
- self.merchant_key_store
- .lock()
- .await
- .iter()
- .find(|merchant_key| merchant_key.merchant_id == *merchant_id)
- .cloned()
- .ok_or(errors::StorageError::ValueNotFound(String::from(
- "merchant_key_store",
- )))?
- .convert(state, key, merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }
-
- async fn delete_merchant_key_store_by_merchant_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- ) -> CustomResult<bool, errors::StorageError> {
- let mut merchant_key_stores = self.merchant_key_store.lock().await;
- let index = merchant_key_stores
- .iter()
- .position(|mks| mks.merchant_id == *merchant_id)
- .ok_or(errors::StorageError::ValueNotFound(format!(
- "No merchant key store found for merchant_id = {merchant_id:?}",
- )))?;
- merchant_key_stores.remove(index);
- Ok(true)
- }
-
- #[cfg(feature = "olap")]
- async fn list_multiple_key_stores(
- &self,
- state: &KeyManagerState,
- merchant_ids: Vec<common_utils::id_type::MerchantId>,
- key: &Secret<Vec<u8>>,
- ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
- let merchant_key_stores = self.merchant_key_store.lock().await;
- futures::future::try_join_all(
- merchant_key_stores
- .iter()
- .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id))
- .map(|merchant_key| async {
- merchant_key
- .to_owned()
- .convert(state, key, merchant_key.merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }),
- )
- .await
- }
- async fn get_all_key_stores(
- &self,
- state: &KeyManagerState,
- key: &Secret<Vec<u8>>,
- _from: u32,
- _to: u32,
- ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
- let merchant_key_stores = self.merchant_key_store.lock().await;
-
- futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async {
- merchant_key
- .to_owned()
- .convert(state, key, merchant_key.merchant_id.clone().into())
- .await
- .change_context(errors::StorageError::DecryptionError)
- }))
- .await
- }
-}
+pub use hyperswitch_domain_models::merchant_key_store::{self, MerchantKeyStoreInterface};
#[cfg(test)]
mod tests {
@@ -325,7 +9,7 @@ mod tests {
use tokio::sync::oneshot;
use crate::{
- db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb},
+ db::{merchant_key_store::MerchantKeyStoreInterface, MockDb},
routes::{
self,
app::{settings::Settings, StorageImpl},
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index b7bf1b9f0f..27ba1fc764 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -1,14 +1,13 @@
use std::collections::HashMap;
+use common_utils::types::TenantConfig;
use error_stack::ResultExt;
use events::{EventsError, Message, MessagingInterface};
+use hyperswitch_interfaces::events as events_interfaces;
use masking::ErasedMaskSerialize;
use router_env::logger;
use serde::{Deserialize, Serialize};
-use storage_impl::{
- config::TenantConfig,
- errors::{ApplicationError, StorageError, StorageResult},
-};
+use storage_impl::errors::{ApplicationError, StorageError, StorageResult};
use time::PrimitiveDateTime;
use crate::{
@@ -66,6 +65,12 @@ impl Default for EventsHandler {
}
}
+impl events_interfaces::EventHandlerInterface for EventsHandler {
+ fn log_connector_event(&self, event: &events_interfaces::connector_api_logs::ConnectorEvent) {
+ self.log_event(event);
+ }
+}
+
impl EventsConfig {
pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> {
Ok(match self {
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 3e6d6bb887..36a1b02b61 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -8,7 +8,7 @@ use api_models::routing::RuleMigrationQuery;
use common_enums::{ExecutionMode, TransactionType};
#[cfg(feature = "partial-auth")]
use common_utils::crypto::Blake3;
-use common_utils::id_type;
+use common_utils::{id_type, types::TenantConfig};
#[cfg(feature = "email")]
use external_services::email::{
no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService,
@@ -27,7 +27,7 @@ use hyperswitch_interfaces::{
};
use router_env::tracing_actix_web::RequestId;
use scheduler::SchedulerInterface;
-use storage_impl::{config::TenantConfig, redis::RedisStore, MockDb};
+use storage_impl::{redis::RedisStore, MockDb};
use tokio::sync::oneshot;
use self::settings::Tenant;
@@ -203,7 +203,7 @@ impl SessionStateInfo for SessionState {
self.event_handler.clone()
}
fn get_request_id(&self) -> Option<String> {
- self.api_client.get_request_id()
+ self.api_client.get_request_id_str()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id);
@@ -250,6 +250,31 @@ impl SessionStateInfo for SessionState {
self.global_store.to_owned()
}
}
+
+impl hyperswitch_interfaces::api_client::ApiClientWrapper for SessionState {
+ fn get_api_client(&self) -> &dyn crate::services::ApiClient {
+ self.api_client.as_ref()
+ }
+ fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy {
+ self.conf.proxy.clone()
+ }
+ fn get_request_id(&self) -> Option<RequestId> {
+ self.request_id
+ }
+ fn get_request_id_str(&self) -> Option<String> {
+ self.request_id
+ .map(|req_id| req_id.as_hyphenated().to_string())
+ }
+ fn get_tenant(&self) -> Tenant {
+ self.tenant.clone()
+ }
+ fn get_connectors(&self) -> hyperswitch_domain_models::connector_endpoints::Connectors {
+ self.conf.connectors.clone()
+ }
+ fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface {
+ &self.event_handler
+ }
+}
#[derive(Clone)]
pub struct AppState {
pub flow_name: String,
@@ -317,7 +342,7 @@ impl AppStateInfo for AppState {
self.api_client.add_flow_name(flow_name);
}
fn get_request_id(&self) -> Option<String> {
- self.api_client.get_request_id()
+ self.api_client.get_request_id_str()
}
}
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 1383768ed8..d94ab9b514 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -17,6 +17,7 @@ pub mod openidconnect;
use std::sync::Arc;
+use common_utils::types::TenantConfig;
use error_stack::ResultExt;
pub use hyperswitch_interfaces::connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
@@ -24,7 +25,7 @@ pub use hyperswitch_interfaces::connector_integration_v2::{
use masking::{ExposeInterface, StrongSecret};
#[cfg(feature = "kv_store")]
use storage_impl::kv_router_store::KVRouterStore;
-use storage_impl::{config::TenantConfig, errors::StorageResult, redis::RedisStore, RouterStore};
+use storage_impl::{errors::StorageResult, redis::RedisStore, RouterStore};
use tokio::sync::oneshot;
pub use self::{api::*, encryption::*};
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 230250400b..d92633ecae 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -20,11 +20,8 @@ pub use client::{ApiClient, MockApiClient, ProxyClient};
pub use common_enums::enums::PaymentAction;
pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
- consts::{
- DEFAULT_TENANT, TENANT_HEADER, X_CONNECTOR_NAME, X_FLOW_NAME, X_HS_LATENCY, X_REQUEST_ID,
- },
+ consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
- request::RequestContent,
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types;
@@ -43,14 +40,17 @@ pub use hyperswitch_interfaces::{
ConnectorIntegrationAny, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation,
},
+ api_client::{
+ call_connector_api, execute_connector_processing_step, handle_response,
+ handle_ucs_response, store_raw_connector_response_if_required,
+ },
connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
},
};
-use masking::{Maskable, PeekInterface, Secret};
+use masking::{Maskable, PeekInterface};
use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
use serde::Serialize;
-use serde_json::json;
use tera::{Context, Error as TeraError, Tera};
use super::{
@@ -59,26 +59,18 @@ use super::{
};
use crate::{
configs::Settings,
- consts,
core::{
api_locking,
errors::{self, CustomResult},
- payments, unified_connector_service, utils as core_utils,
- },
- events::{
- api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
- connector_api_logs::ConnectorEvent,
},
+ events::api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
headers, logger,
routes::{
app::{AppStateInfo, ReqState, SessionStateInfo},
metrics, AppState, SessionState,
},
- services::{
- connector_integration_interface::RouterDataConversion,
- generic_link_response::build_generic_link_html,
- },
- types::{self, api, ErrorResponse},
+ services::generic_link_response::build_generic_link_html,
+ types::api,
utils,
};
@@ -138,516 +130,9 @@ pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> =
pub type BoxedGiftCardBalanceCheckIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GiftCardBalanceCheckFlowData, Req, Res>;
-/// Handle UCS webhook response processing
-fn handle_ucs_response<T, Req, Resp>(
- router_data: types::RouterData<T, Req, Resp>,
- transform_data_bytes: Vec<u8>,
-) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
-where
- T: Clone + Debug + 'static,
- Req: Debug + Clone + 'static,
- Resp: Debug + Clone + 'static,
-{
- let webhook_transform_data: unified_connector_service::WebhookTransformData =
- serde_json::from_slice(&transform_data_bytes)
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)
- .attach_printable("Failed to deserialize UCS webhook transform data")?;
-
- let webhook_content = webhook_transform_data
- .webhook_content
- .ok_or(errors::ConnectorError::ResponseDeserializationFailed)
- .attach_printable("UCS webhook transform data missing webhook_content")?;
-
- let payment_get_response = match webhook_content.content {
- Some(unified_connector_service_client::payments::webhook_response_content::Content::PaymentsResponse(payments_response)) => {
- Ok(payments_response)
- },
- Some(unified_connector_service_client::payments::webhook_response_content::Content::RefundsResponse(_)) => {
- Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains refund response but payment processing was expected".to_string().into())).into())
- },
- Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => {
- Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains dispute response but payment processing was expected".to_string().into())).into())
- },
- Some(unified_connector_service_client::payments::webhook_response_content::Content::IncompleteTransformation(_)) => {
- Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains incomplete transformation but payment processing was expected".to_string().into())).into())
- },
- None => {
- Err(errors::ConnectorError::ResponseDeserializationFailed)
- .attach_printable("UCS webhook content missing payments_response")
- }
- }?;
-
- let (router_data_response, status_code) =
- unified_connector_service::handle_unified_connector_service_response_for_payment_get(
- payment_get_response.clone(),
- )
- .change_context(errors::ConnectorError::ProcessingStepFailed(None))
- .attach_printable("Failed to process UCS webhook response using PSync handler")?;
-
- let mut updated_router_data = router_data;
- let router_data_response = router_data_response.map(|(response, status)| {
- updated_router_data.status = status;
- response
- });
-
- let _ = router_data_response.map_err(|error_response| {
- updated_router_data.response = Err(error_response);
- });
- updated_router_data.raw_connector_response =
- payment_get_response.raw_connector_response.map(Secret::new);
- updated_router_data.connector_http_status_code = Some(status_code);
-
- Ok(updated_router_data)
-}
-
-fn store_raw_connector_response_if_required<T, Req, Resp>(
- return_raw_connector_response: Option<bool>,
- router_data: &mut types::RouterData<T, Req, Resp>,
- body: &types::Response,
-) -> CustomResult<(), errors::ConnectorError>
-where
- T: Clone + Debug + 'static,
- Req: Debug + Clone + 'static,
- Resp: Debug + Clone + 'static,
-{
- if return_raw_connector_response == Some(true) {
- let mut decoded = String::from_utf8(body.response.as_ref().to_vec())
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- if decoded.starts_with('\u{feff}') {
- decoded = decoded.trim_start_matches('\u{feff}').to_string();
- }
- router_data.raw_connector_response = Some(Secret::new(decoded));
- }
- Ok(())
-}
-
pub type BoxedSubscriptionConnectorIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::SubscriptionCreateData, Req, Res>;
-/// Handle the flow by interacting with connector module
-/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
-/// In other cases, It will be created if required, even if it is not passed
-#[instrument(skip_all, fields(connector_name, payment_method))]
-pub async fn execute_connector_processing_step<
- 'b,
- 'a,
- T,
- ResourceCommonData: Clone + RouterDataConversion<T, Req, Resp> + 'static,
- Req: Debug + Clone + 'static,
- Resp: Debug + Clone + 'static,
->(
- state: &'b SessionState,
- connector_integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>,
- req: &'b types::RouterData<T, Req, Resp>,
- call_connector_action: payments::CallConnectorAction,
- connector_request: Option<Request>,
- return_raw_connector_response: Option<bool>,
-) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
-where
- T: Clone + Debug + 'static,
- // BoxedConnectorIntegration<T, Req, Resp>: 'b,
-{
- // If needed add an error stack as follows
- // connector_integration.build_request(req).attach_printable("Failed to build request");
- tracing::Span::current().record("connector_name", &req.connector);
- tracing::Span::current().record("payment_method", req.payment_method.to_string());
- logger::debug!(connector_request=?connector_request);
- let mut router_data = req.clone();
- match call_connector_action {
- payments::CallConnectorAction::HandleResponse(res) => {
- let response = types::Response {
- headers: None,
- response: res.into(),
- status_code: 200,
- };
- connector_integration.handle_response(req, None, response)
- }
- payments::CallConnectorAction::UCSHandleResponse(transform_data_bytes) => {
- handle_ucs_response(router_data, transform_data_bytes)
- }
- payments::CallConnectorAction::Avoid => Ok(router_data),
- payments::CallConnectorAction::StatusUpdate {
- status,
- error_code,
- error_message,
- } => {
- router_data.status = status;
- let error_response = if error_code.is_some() | error_message.is_some() {
- Some(ErrorResponse {
- code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- status_code: 200, // This status code is ignored in redirection response it will override with 302 status code.
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- network_advice_code: None,
- network_decline_code: None,
- network_error_message: None,
- connector_metadata: None,
- })
- } else {
- None
- };
- router_data.response = error_response.map(Err).unwrap_or(router_data.response);
- Ok(router_data)
- }
- payments::CallConnectorAction::Trigger => {
- metrics::CONNECTOR_CALL_COUNT.add(
- 1,
- router_env::metric_attributes!(
- ("connector", req.connector.to_string()),
- (
- "flow",
- core_utils::get_flow_name::<T>()
- .unwrap_or_else(|_| "UnknownFlow".to_string())
- ),
- ),
- );
-
- let connector_request = match connector_request {
- Some(connector_request) => Some(connector_request),
- None => connector_integration
- .build_request(req, &state.conf.connectors)
- .inspect_err(|error| {
- if matches!(
- error.current_context(),
- &errors::ConnectorError::RequestEncodingFailed
- | &errors::ConnectorError::RequestEncodingFailedWithReason(_)
- ) {
- metrics::REQUEST_BUILD_FAILURE.add(
- 1,
- router_env::metric_attributes!((
- "connector",
- req.connector.clone()
- )),
- )
- }
- })?,
- };
-
- match connector_request {
- Some(mut request) => {
- let masked_request_body = match &request.body {
- Some(request) => match request {
- RequestContent::Json(i)
- | RequestContent::FormUrlEncoded(i)
- | RequestContent::Xml(i) => i
- .masked_serialize()
- .unwrap_or(json!({ "error": "failed to mask serialize"})),
- RequestContent::FormData((_, i)) => i
- .masked_serialize()
- .unwrap_or(json!({ "error": "failed to mask serialize"})),
- RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}),
- },
- None => serde_json::Value::Null,
- };
- let flow_name = core_utils::get_flow_name::<T>()
- .unwrap_or_else(|_| "UnknownFlow".to_string());
-
- request.headers.insert((
- X_FLOW_NAME.to_string(),
- Maskable::Masked(Secret::new(flow_name.to_string())),
- ));
-
- let connector_name = req.connector.clone();
- request.headers.insert((
- X_CONNECTOR_NAME.to_string(),
- Maskable::Masked(Secret::new(connector_name.clone().to_string())),
- ));
- state.request_id.as_ref().map(|id| {
- let request_id = id.to_string();
- request.headers.insert((
- X_REQUEST_ID.to_string(),
- Maskable::Normal(request_id.clone()),
- ));
- request_id
- });
- let request_url = request.url.clone();
- let request_method = request.method;
- let current_time = Instant::now();
- let response =
- call_connector_api(state, request, "execute_connector_processing_step")
- .await;
- let external_latency = current_time.elapsed().as_millis();
- logger::info!(raw_connector_request=?masked_request_body);
- let status_code = response
- .as_ref()
- .map(|i| {
- i.as_ref()
- .map_or_else(|value| value.status_code, |value| value.status_code)
- })
- .unwrap_or_default();
- let mut connector_event = ConnectorEvent::new(
- state.tenant.tenant_id.clone(),
- req.connector.clone(),
- std::any::type_name::<T>(),
- masked_request_body,
- request_url,
- request_method,
- req.payment_id.clone(),
- req.merchant_id.clone(),
- state.request_id.as_ref(),
- external_latency,
- req.refund_id.clone(),
- req.dispute_id.clone(),
- status_code,
- );
-
- match response {
- Ok(body) => {
- let response = match body {
- Ok(body) => {
- let connector_http_status_code = Some(body.status_code);
- let handle_response_result = connector_integration
- .handle_response(req, Some(&mut connector_event), body.clone())
- .inspect_err(|error| {
- if error.current_context()
- == &errors::ConnectorError::ResponseDeserializationFailed
- {
- metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
-
- 1,
- router_env::metric_attributes!((
- "connector",
- req.connector.clone(),
- )),
- )
- }
- });
- match handle_response_result {
- Ok(mut data) => {
- state.event_handler().log_event(&connector_event);
- data.connector_http_status_code =
- connector_http_status_code;
- // Add up multiple external latencies in case of multiple external calls within the same request.
- data.external_latency = Some(
- data.external_latency
- .map_or(external_latency, |val| {
- val + external_latency
- }),
- );
-
- store_raw_connector_response_if_required(
- return_raw_connector_response,
- &mut data,
- &body,
- )?;
-
- Ok(data)
- }
- Err(err) => {
- connector_event
- .set_error(json!({"error": err.to_string()}));
-
- state.event_handler().log_event(&connector_event);
- Err(err)
- }
- }?
- }
- Err(body) => {
- router_data.connector_http_status_code = Some(body.status_code);
- router_data.external_latency = Some(
- router_data
- .external_latency
- .map_or(external_latency, |val| val + external_latency),
- );
- metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
- 1,
- router_env::metric_attributes!((
- "connector",
- req.connector.clone(),
- )),
- );
-
- store_raw_connector_response_if_required(
- return_raw_connector_response,
- &mut router_data,
- &body,
- )?;
-
- let error = match body.status_code {
- 500..=511 => {
- let error_res = connector_integration
- .get_5xx_error_response(
- body,
- Some(&mut connector_event),
- )?;
- state.event_handler().log_event(&connector_event);
- error_res
- }
- _ => {
- let error_res = connector_integration
- .get_error_response(
- body,
- Some(&mut connector_event),
- )?;
- if let Some(status) = error_res.attempt_status {
- router_data.status = status;
- };
- state.event_handler().log_event(&connector_event);
- error_res
- }
- };
-
- router_data.response = Err(error);
-
- router_data
- }
- };
- Ok(response)
- }
- Err(error) => {
- connector_event.set_error(json!({"error": error.to_string()}));
- state.event_handler().log_event(&connector_event);
- if error.current_context().is_upstream_timeout() {
- let error_response = ErrorResponse {
- code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
- message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
- reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
- status_code: 504,
- attempt_status: None,
- connector_transaction_id: None,
- network_advice_code: None,
- network_decline_code: None,
- network_error_message: None,
- connector_metadata: None,
- };
- router_data.response = Err(error_response);
- router_data.connector_http_status_code = Some(504);
- router_data.external_latency = Some(
- router_data
- .external_latency
- .map_or(external_latency, |val| val + external_latency),
- );
- Ok(router_data)
- } else {
- Err(error.change_context(
- errors::ConnectorError::ProcessingStepFailed(None),
- ))
- }
- }
- }
- }
- None => Ok(router_data),
- }
- }
- }
-}
-
-#[instrument(skip_all)]
-pub async fn call_connector_api(
- state: &SessionState,
- request: Request,
- flow_name: &str,
-) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
- let current_time = Instant::now();
- let headers = request.headers.clone();
- let url = request.url.clone();
- let response = state
- .api_client
- .send_request(state, request, None, true)
- .await;
-
- match response.as_ref() {
- Ok(resp) => {
- let status_code = resp.status().as_u16();
- let elapsed_time = current_time.elapsed();
- logger::info!(
- ?headers,
- url,
- status_code,
- flow=?flow_name,
- ?elapsed_time
- );
- }
- Err(err) => {
- logger::info!(
- call_connector_api_error=?err
- );
- }
- }
-
- handle_response(response).await
-}
-
-#[instrument(skip_all)]
-async fn handle_response(
- response: CustomResult<reqwest::Response, errors::ApiClientError>,
-) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
- response
- .map(|response| async {
- logger::info!(?response);
- let status_code = response.status().as_u16();
- let headers = Some(response.headers().to_owned());
- match status_code {
- 200..=202 | 302 | 204 => {
- // If needed add log line
- // logger:: error!( error_parsing_response=?err);
- let response = response
- .bytes()
- .await
- .change_context(errors::ApiClientError::ResponseDecodingFailed)
- .attach_printable("Error while waiting for response")?;
- Ok(Ok(types::Response {
- headers,
- response,
- status_code,
- }))
- }
-
- status_code @ 500..=599 => {
- let bytes = response.bytes().await.map_err(|error| {
- report!(error)
- .change_context(errors::ApiClientError::ResponseDecodingFailed)
- .attach_printable("Client error response received")
- })?;
- // let error = match status_code {
- // 500 => errors::ApiClientError::InternalServerErrorReceived,
- // 502 => errors::ApiClientError::BadGatewayReceived,
- // 503 => errors::ApiClientError::ServiceUnavailableReceived,
- // 504 => errors::ApiClientError::GatewayTimeoutReceived,
- // _ => errors::ApiClientError::UnexpectedServerResponse,
- // };
- Ok(Err(types::Response {
- headers,
- response: bytes,
- status_code,
- }))
- }
-
- status_code @ 400..=499 => {
- let bytes = response.bytes().await.map_err(|error| {
- report!(error)
- .change_context(errors::ApiClientError::ResponseDecodingFailed)
- .attach_printable("Client error response received")
- })?;
- /* let error = match status_code {
- 400 => errors::ApiClientError::BadRequestReceived(bytes),
- 401 => errors::ApiClientError::UnauthorizedReceived(bytes),
- 403 => errors::ApiClientError::ForbiddenReceived,
- 404 => errors::ApiClientError::NotFoundReceived(bytes),
- 405 => errors::ApiClientError::MethodNotAllowedReceived,
- 408 => errors::ApiClientError::RequestTimeoutReceived,
- 422 => errors::ApiClientError::UnprocessableEntityReceived(bytes),
- 429 => errors::ApiClientError::TooManyRequestsReceived,
- _ => errors::ApiClientError::UnexpectedServerResponse,
- };
- Err(report!(error).attach_printable("Client error response received"))
- */
- Ok(Err(types::Response {
- headers,
- response: bytes,
- status_code,
- }))
- }
-
- _ => Err(report!(errors::ApiClientError::UnexpectedServerResponse)
- .attach_printable("Unexpected response from server")),
- }
- })?
- .await
-}
-
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplicationRedirectResponse {
pub url: String,
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index 9e54e673b9..fd736d9fe0 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -4,72 +4,22 @@ use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
pub use external_services::http_client::{self, client};
use http::{HeaderValue, Method};
-use hyperswitch_interfaces::types::Proxy;
+pub use hyperswitch_interfaces::{
+ api_client::{ApiClient, ApiClientWrapper, RequestBuilder},
+ types::Proxy,
+};
use masking::PeekInterface;
use reqwest::multipart::Form;
use router_env::tracing_actix_web::RequestId;
use super::{request::Maskable, Request};
-use crate::{
- core::errors::{ApiClientError, CustomResult},
- routes::SessionState,
-};
-
-pub trait RequestBuilder: Send + Sync {
- fn json(&mut self, body: serde_json::Value);
- fn url_encoded_form(&mut self, body: serde_json::Value);
- fn timeout(&mut self, timeout: Duration);
- fn multipart(&mut self, form: Form);
- fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError>;
- fn send(
- self,
- ) -> CustomResult<
- Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>,
- ApiClientError,
- >;
-}
-
-#[async_trait::async_trait]
-pub trait ApiClient: dyn_clone::DynClone
-where
- Self: Send + Sync,
-{
- fn request(
- &self,
- method: Method,
- url: String,
- ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
-
- fn request_with_certificate(
- &self,
- method: Method,
- url: String,
- certificate: Option<masking::Secret<String>>,
- certificate_key: Option<masking::Secret<String>>,
- ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
-
- async fn send_request(
- &self,
- state: &SessionState,
- request: Request,
- option_timeout_secs: Option<u64>,
- forward_to_kafka: bool,
- ) -> CustomResult<reqwest::Response, ApiClientError>;
-
- fn add_request_id(&mut self, request_id: RequestId);
-
- fn get_request_id(&self) -> Option<String>;
-
- fn add_flow_name(&mut self, flow_name: String);
-}
-
-dyn_clone::clone_trait_object!(ApiClient);
+use crate::core::errors::{ApiClientError, CustomResult};
#[derive(Clone)]
pub struct ProxyClient {
proxy_config: Proxy,
client: reqwest::Client,
- request_id: Option<String>,
+ request_id: Option<RequestId>,
}
impl ProxyClient {
@@ -186,23 +136,26 @@ impl ApiClient for ProxyClient {
}
async fn send_request(
&self,
- state: &SessionState,
+ api_client: &dyn ApiClientWrapper,
request: Request,
option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError> {
- http_client::send_request(&state.conf.proxy, request, option_timeout_secs)
+ http_client::send_request(&api_client.get_proxy(), request, option_timeout_secs)
.await
.switch()
}
fn add_request_id(&mut self, request_id: RequestId) {
+ self.request_id = Some(request_id);
+ }
+
+ fn get_request_id(&self) -> Option<RequestId> {
self.request_id
- .replace(request_id.as_hyphenated().to_string());
}
- fn get_request_id(&self) -> Option<String> {
- self.request_id.clone()
+ fn get_request_id_str(&self) -> Option<String> {
+ self.request_id.map(|id| id.as_hyphenated().to_string())
}
fn add_flow_name(&mut self, _flow_name: String) {}
@@ -236,7 +189,7 @@ impl ApiClient for MockApiClient {
async fn send_request(
&self,
- _state: &SessionState,
+ _state: &dyn ApiClientWrapper,
_request: Request,
_option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
@@ -249,7 +202,12 @@ impl ApiClient for MockApiClient {
// [#2066]: Add Mock implementation for ApiClient
}
- fn get_request_id(&self) -> Option<String> {
+ fn get_request_id(&self) -> Option<RequestId> {
+ // [#2066]: Add Mock implementation for ApiClient
+ None
+ }
+
+ fn get_request_id_str(&self) -> Option<String> {
// [#2066]: Add Mock implementation for ApiClient
None
}
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 8a7613f344..c724016abe 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -1,6 +1,6 @@
use std::{collections::HashMap, sync::Arc};
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, types::TenantConfig};
use error_stack::{report, ResultExt};
use events::{EventsError, Message, MessagingInterface};
use num_traits::ToPrimitive;
@@ -10,7 +10,6 @@ use rdkafka::{
producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer},
};
use serde_json::Value;
-use storage_impl::config::TenantConfig;
#[cfg(feature = "payouts")]
pub mod payout;
use diesel_models::fraud_check::FraudCheck;
diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml
index 2b77423fa4..8bc23f4dbb 100644
--- a/crates/storage_impl/Cargo.toml
+++ b/crates/storage_impl/Cargo.toml
@@ -8,9 +8,10 @@ readme = "README.md"
license.workspace = true
[features]
-default = ["olap", "oltp"]
+default = ["olap", "oltp", "accounts_cache"]
dynamic_routing = []
oltp = []
+accounts_cache = []
olap = ["hyperswitch_domain_models/olap"]
payouts = ["hyperswitch_domain_models/payouts"]
v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "common_utils/v1"]
diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rs
new file mode 100644
index 0000000000..add7ece931
--- /dev/null
+++ b/crates/storage_impl/src/business_profile.rs
@@ -0,0 +1,482 @@
+use common_utils::ext_traits::AsyncExt;
+use diesel_models::business_profile::{self, ProfileUpdateInternal};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ behaviour::{Conversion, ReverseConversion},
+ business_profile as domain,
+ business_profile::ProfileInterface,
+ merchant_key_store::MerchantKeyStore,
+};
+use router_env::{instrument, tracing};
+
+use crate::{
+ kv_router_store,
+ utils::{pg_accounts_connection_read, pg_accounts_connection_write},
+ CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> ProfileInterface for kv_router_store::KVRouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_business_profile(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ business_profile: domain::Profile,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.router_store
+ .insert_business_profile(key_manager_state, merchant_key_store, business_profile)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_business_profile_by_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.router_store
+ .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id)
+ .await
+ }
+
+ async fn find_business_profile_by_merchant_id_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.router_store
+ .find_business_profile_by_merchant_id_profile_id(
+ key_manager_state,
+ merchant_key_store,
+ merchant_id,
+ profile_id,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_name: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.router_store
+ .find_business_profile_by_profile_name_merchant_id(
+ key_manager_state,
+ merchant_key_store,
+ profile_name,
+ merchant_id,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_profile_by_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ current_state: domain::Profile,
+ profile_update: domain::ProfileUpdate,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.router_store
+ .update_profile_by_profile_id(
+ key_manager_state,
+ merchant_key_store,
+ current_state,
+ profile_update,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_profile_by_profile_id_merchant_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ self.router_store
+ .delete_profile_by_profile_id_merchant_id(profile_id, merchant_id)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn list_profile_by_merchant_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<domain::Profile>, StorageError> {
+ self.router_store
+ .list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id)
+ .await
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_business_profile(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ business_profile: domain::Profile,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+ business_profile
+ .construct_new()
+ .await
+ .change_context(StorageError::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn find_business_profile_by_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let conn = pg_accounts_connection_read(self).await?;
+ self.call_database(
+ key_manager_state,
+ merchant_key_store,
+ business_profile::Profile::find_by_profile_id(&conn, profile_id),
+ )
+ .await
+ }
+
+ async fn find_business_profile_by_merchant_id_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let conn = pg_accounts_connection_read(self).await?;
+ self.call_database(
+ key_manager_state,
+ merchant_key_store,
+ business_profile::Profile::find_by_merchant_id_profile_id(
+ &conn,
+ merchant_id,
+ profile_id,
+ ),
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_name: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let conn = pg_accounts_connection_read(self).await?;
+ self.call_database(
+ key_manager_state,
+ merchant_key_store,
+ business_profile::Profile::find_by_profile_name_merchant_id(
+ &conn,
+ profile_name,
+ merchant_id,
+ ),
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_profile_by_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ current_state: domain::Profile,
+ profile_update: domain::ProfileUpdate,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+ Conversion::convert(current_state)
+ .await
+ .change_context(StorageError::EncryptionError)?
+ .update_by_profile_id(&conn, ProfileUpdateInternal::from(profile_update))
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_profile_by_profile_id_merchant_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+ business_profile::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn list_profile_by_merchant_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<domain::Profile>, StorageError> {
+ let conn = pg_accounts_connection_read(self).await?;
+ self.find_resources(
+ key_manager_state,
+ merchant_key_store,
+ business_profile::Profile::list_profile_by_merchant_id(&conn, merchant_id),
+ )
+ .await
+ }
+}
+
+#[async_trait::async_trait]
+impl ProfileInterface for MockDb {
+ type Error = StorageError;
+ async fn insert_business_profile(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ business_profile: domain::Profile,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let stored_business_profile = Conversion::convert(business_profile)
+ .await
+ .change_context(StorageError::EncryptionError)?;
+
+ self.business_profiles
+ .lock()
+ .await
+ .push(stored_business_profile.clone());
+
+ stored_business_profile
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ async fn find_business_profile_by_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.business_profiles
+ .lock()
+ .await
+ .iter()
+ .find(|business_profile| business_profile.get_id() == profile_id)
+ .cloned()
+ .async_map(|business_profile| async {
+ business_profile
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ StorageError::ValueNotFound(format!(
+ "No business profile found for profile_id = {profile_id:?}"
+ ))
+ .into(),
+ )
+ }
+
+ async fn find_business_profile_by_merchant_id_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.business_profiles
+ .lock()
+ .await
+ .iter()
+ .find(|business_profile| {
+ business_profile.merchant_id == *merchant_id
+ && business_profile.get_id() == profile_id
+ })
+ .cloned()
+ .async_map(|business_profile| async {
+ business_profile
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ StorageError::ValueNotFound(format!(
+ "No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}"
+ ))
+ .into(),
+ )
+ }
+
+ async fn update_profile_by_profile_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ current_state: domain::Profile,
+ profile_update: domain::ProfileUpdate,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ let profile_id = current_state.get_id().to_owned();
+ self.business_profiles
+ .lock()
+ .await
+ .iter_mut()
+ .find(|business_profile| business_profile.get_id() == current_state.get_id())
+ .async_map(|business_profile| async {
+ let profile_updated = ProfileUpdateInternal::from(profile_update).apply_changeset(
+ Conversion::convert(current_state)
+ .await
+ .change_context(StorageError::EncryptionError)?,
+ );
+ *business_profile = profile_updated.clone();
+
+ profile_updated
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ StorageError::ValueNotFound(format!(
+ "No business profile found for profile_id = {profile_id:?}",
+ ))
+ .into(),
+ )
+ }
+
+ async fn delete_profile_by_profile_id_merchant_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ let mut business_profiles = self.business_profiles.lock().await;
+ let index = business_profiles
+ .iter()
+ .position(|business_profile| {
+ business_profile.get_id() == profile_id
+ && business_profile.merchant_id == *merchant_id
+ })
+ .ok_or::<StorageError>(StorageError::ValueNotFound(format!(
+ "No business profile found for profile_id = {profile_id:?} and merchant_id = {merchant_id:?}"
+ )))?;
+ business_profiles.remove(index);
+ Ok(true)
+ }
+
+ async fn list_profile_by_merchant_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<domain::Profile>, StorageError> {
+ let business_profiles = self
+ .business_profiles
+ .lock()
+ .await
+ .iter()
+ .filter(|business_profile| business_profile.merchant_id == *merchant_id)
+ .cloned()
+ .collect::<Vec<_>>();
+
+ let mut domain_business_profiles = Vec::with_capacity(business_profiles.len());
+
+ for business_profile in business_profiles {
+ let domain_profile = business_profile
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?;
+ domain_business_profiles.push(domain_profile);
+ }
+
+ Ok(domain_business_profiles)
+ }
+
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &MerchantKeyStore,
+ profile_name: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<domain::Profile, StorageError> {
+ self.business_profiles
+ .lock()
+ .await
+ .iter()
+ .find(|business_profile| {
+ business_profile.profile_name == profile_name
+ && business_profile.merchant_id == *merchant_id
+ })
+ .cloned()
+ .async_map(|business_profile| async {
+ business_profile
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ StorageError::ValueNotFound(format!(
+ "No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}"
+
+ ))
+ .into(),
+ )
+ }
+}
diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs
index 857c23161e..64a92348ce 100644
--- a/crates/storage_impl/src/config.rs
+++ b/crates/storage_impl/src/config.rs
@@ -1,4 +1,4 @@
-use common_utils::{id_type, DbConnectionParams};
+use common_utils::DbConnectionParams;
use masking::Secret;
#[derive(Debug, Clone, serde::Deserialize)]
@@ -33,14 +33,6 @@ impl DbConnectionParams for Database {
}
}
-pub trait TenantConfig: Send + Sync {
- fn get_tenant_id(&self) -> &id_type::TenantId;
- fn get_schema(&self) -> &str;
- fn get_accounts_schema(&self) -> &str;
- fn get_redis_key_prefix(&self) -> &str;
- fn get_clickhouse_database(&self) -> &str;
-}
-
#[derive(Debug, serde::Deserialize, Clone, Copy, Default)]
#[serde(rename_all = "PascalCase")]
pub enum QueueStrategy {
diff --git a/crates/storage_impl/src/configs.rs b/crates/storage_impl/src/configs.rs
new file mode 100644
index 0000000000..e1073df87a
--- /dev/null
+++ b/crates/storage_impl/src/configs.rs
@@ -0,0 +1,285 @@
+use diesel_models::configs as storage;
+use error_stack::report;
+use hyperswitch_domain_models::configs::ConfigInterface;
+use router_env::{instrument, tracing};
+
+use crate::{
+ connection,
+ errors::StorageError,
+ kv_router_store,
+ redis::{
+ cache,
+ cache::{CacheKind, CONFIG_CACHE},
+ },
+ store::ConfigUpdateInternal,
+ CustomResult, DatabaseStore, MockDb, RouterStore,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_config(
+ &self,
+ config: storage::ConfigNew,
+ ) -> CustomResult<storage::Config, Self::Error> {
+ 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(
+ &self,
+ key: &str,
+ config_update: storage::ConfigUpdate,
+ ) -> CustomResult<storage::Config, StorageError> {
+ self.router_store
+ .update_config_by_key(key, config_update)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_config_by_key_from_db(
+ &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
+ }
+
+ #[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>,
+ ) -> CustomResult<storage::Config, StorageError> {
+ self.router_store
+ .find_config_by_key_unwrap_or(key, default_config)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
+ self.router_store.delete_config_by_key(key).await
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> ConfigInterface for RouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_config(
+ &self,
+ config: storage::ConfigNew,
+ ) -> CustomResult<storage::Config, StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ let inserted = config
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ cache::redact_from_redis_and_publish(self, [CacheKind::Config((&inserted.key).into())])
+ .await?;
+
+ 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(
+ &self,
+ 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 {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Config::find_by_key(&conn, key)
+ .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
+ }
+
+ #[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>,
+ ) -> CustomResult<storage::Config, StorageError> {
+ let find_else_unwrap_or = || 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),
+ 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)
+ } else {
+ Err(err)
+ }
+ }
+ }
+ };
+
+ cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ let deleted = storage::Config::delete_by_key(&conn, key)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ cache::redact_from_redis_and_publish(self, [CacheKind::Config((&deleted.key).into())])
+ .await?;
+
+ Ok(deleted)
+ }
+}
+
+#[async_trait::async_trait]
+impl ConfigInterface for MockDb {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_config(
+ &self,
+ config: storage::ConfigNew,
+ ) -> CustomResult<storage::Config, Self::Error> {
+ let mut configs = self.configs.lock().await;
+
+ let config_new = storage::Config {
+ key: config.key,
+ config: config.config,
+ };
+ configs.push(config_new.clone());
+ 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,
+ config_update: storage::ConfigUpdate,
+ ) -> CustomResult<storage::Config, Self::Error> {
+ let result = self
+ .configs
+ .lock()
+ .await
+ .iter_mut()
+ .find(|c| c.key == key)
+ .ok_or_else(|| {
+ StorageError::ValueNotFound("cannot find config to update".to_string()).into()
+ })
+ .map(|c| {
+ let config_updated =
+ ConfigUpdateInternal::from(config_update).create_config(c.clone());
+ *c = config_updated.clone();
+ config_updated
+ });
+
+ result
+ }
+
+ async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> {
+ let mut configs = self.configs.lock().await;
+ let result = configs
+ .iter()
+ .position(|c| c.key == key)
+ .map(|index| configs.remove(index))
+ .ok_or_else(|| {
+ StorageError::ValueNotFound("cannot find config to delete".to_string()).into()
+ });
+
+ 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(
+ &self,
+ key: &str,
+ _default_config: Option<String>,
+ ) -> CustomResult<storage::Config, Self::Error> {
+ self.find_config_by_key(key).await
+ }
+
+ async fn find_config_by_key_from_db(
+ &self,
+ key: &str,
+ ) -> CustomResult<storage::Config, Self::Error> {
+ self.find_config_by_key(key).await
+ }
+}
diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rs
index 6761ec7678..9caa84be48 100644
--- a/crates/storage_impl/src/database/store.rs
+++ b/crates/storage_impl/src/database/store.rs
@@ -1,11 +1,11 @@
use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::CustomizeConnection;
-use common_utils::DbConnectionParams;
+use common_utils::{types::TenantConfig, DbConnectionParams};
use diesel::PgConnection;
use error_stack::ResultExt;
use crate::{
- config::{Database, TenantConfig},
+ config::Database,
errors::{StorageError, StorageResult},
};
diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rs
index 7827f3a2a5..7ad2763c8f 100644
--- a/crates/storage_impl/src/kv_router_store.rs
+++ b/crates/storage_impl/src/kv_router_store.rs
@@ -17,8 +17,8 @@ use serde::de;
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
+pub use crate::{database::store::DatabaseStore, mock_db::MockDb};
use crate::{
- config::TenantConfig,
database::store::PgPool,
diesel_error_to_data_error,
errors::{self, RedisErrorExt, StorageResult},
@@ -29,9 +29,8 @@ use crate::{
RedisConnInterface,
},
utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get},
- RouterStore, UniqueConstraints,
+ RouterStore, TenantConfig, UniqueConstraints,
};
-pub use crate::{database::store::DatabaseStore, mock_db::MockDb};
#[derive(Debug, Clone)]
pub struct KVRouterStore<T: DatabaseStore> {
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 5e6483fd1d..691a010b1c 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -1,5 +1,6 @@
use std::{fmt::Debug, sync::Arc};
+use common_utils::types::TenantConfig;
use diesel_models as store;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
@@ -9,9 +10,11 @@ use hyperswitch_domain_models::{
use masking::StrongSecret;
use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore};
mod address;
+pub mod business_profile;
pub mod callback_mapper;
pub mod cards_info;
pub mod config;
+pub mod configs;
pub mod connection;
pub mod customers;
pub mod database;
@@ -20,6 +23,9 @@ pub mod invoice;
pub mod kv_router_store;
pub mod lookup;
pub mod mandate;
+pub mod merchant_account;
+pub mod merchant_connector_account;
+pub mod merchant_key_store;
pub mod metrics;
pub mod mock_db;
pub mod payment_method;
@@ -66,7 +72,7 @@ where
);
async fn new(
config: Self::Config,
- tenant_config: &dyn config::TenantConfig,
+ tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> error_stack::Result<Self, StorageError> {
let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) =
@@ -112,7 +118,7 @@ impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {
impl<T: DatabaseStore> RouterStore<T> {
pub async fn from_config(
db_conf: T::Config,
- tenant_config: &dyn config::TenantConfig,
+ tenant_config: &dyn TenantConfig,
encryption_key: StrongSecret<Vec<u8>>,
cache_store: Arc<RedisStore>,
inmemory_cache_stream: &str,
@@ -256,7 +262,7 @@ impl<T: DatabaseStore> RouterStore<T> {
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` is not set
pub async fn test_store(
db_conf: T::Config,
- tenant_config: &dyn config::TenantConfig,
+ tenant_config: &dyn TenantConfig,
cache_conf: &redis_interface::RedisSettings,
encryption_key: StrongSecret<Vec<u8>>,
) -> error_stack::Result<Self, StorageError> {
diff --git a/crates/storage_impl/src/merchant_account.rs b/crates/storage_impl/src/merchant_account.rs
new file mode 100644
index 0000000000..79f2687396
--- /dev/null
+++ b/crates/storage_impl/src/merchant_account.rs
@@ -0,0 +1,874 @@
+#[cfg(feature = "olap")]
+use std::collections::HashMap;
+
+use common_utils::ext_traits::AsyncExt;
+use diesel_models::merchant_account as storage;
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ behaviour::{Conversion, ReverseConversion},
+ merchant_account::{self as domain, MerchantAccountInterface},
+ merchant_key_store::{MerchantKeyStore, MerchantKeyStoreInterface},
+};
+use masking::PeekInterface;
+use router_env::{instrument, tracing};
+
+#[cfg(feature = "accounts_cache")]
+use crate::redis::{
+ cache,
+ cache::{CacheKind, ACCOUNTS_CACHE},
+};
+#[cfg(feature = "accounts_cache")]
+use crate::RedisConnInterface;
+use crate::{
+ kv_router_store,
+ store::MerchantAccountUpdateInternal,
+ utils::{pg_accounts_connection_read, pg_accounts_connection_write},
+ CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> MerchantAccountInterface for kv_router_store::KVRouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_account: domain::MerchantAccount,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ self.router_store
+ .insert_merchant(state, merchant_account, merchant_key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_merchant_account_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ self.router_store
+ .find_merchant_account_by_merchant_id(state, merchant_id, merchant_key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_merchant(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantAccount,
+ merchant_account: domain::MerchantAccountUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ self.router_store
+ .update_merchant(state, this, merchant_account, merchant_key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_specific_fields_in_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_account: domain::MerchantAccountUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ self.router_store
+ .update_specific_fields_in_merchant(
+ state,
+ merchant_id,
+ merchant_account,
+ merchant_key_store,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_merchant_account_by_publishable_key(
+ &self,
+ state: &KeyManagerState,
+ publishable_key: &str,
+ ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {
+ self.router_store
+ .find_merchant_account_by_publishable_key(state, publishable_key)
+ .await
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ state: &KeyManagerState,
+ organization_id: &common_utils::id_type::OrganizationId,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
+ self.router_store
+ .list_merchant_accounts_by_organization_id(state, organization_id)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_merchant_account_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ self.router_store
+ .delete_merchant_account_by_merchant_id(merchant_id)
+ .await
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_multiple_merchant_accounts(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
+ self.router_store
+ .list_multiple_merchant_accounts(state, merchant_ids)
+ .await
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_merchant_and_org_ids(
+ &self,
+ _state: &KeyManagerState,
+ limit: u32,
+ offset: Option<u32>,
+ ) -> CustomResult<
+ Vec<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::OrganizationId,
+ )>,
+ StorageError,
+ > {
+ self.router_store
+ .list_merchant_and_org_ids(_state, limit, offset)
+ .await
+ }
+
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account: domain::MerchantAccountUpdate,
+ ) -> CustomResult<usize, StorageError> {
+ self.router_store
+ .update_all_merchant_account(merchant_account)
+ .await
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_account: domain::MerchantAccount,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+ merchant_account
+ .construct_new()
+ .await
+ .change_context(StorageError::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn find_merchant_account_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let fetch_func = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ fetch_func()
+ .await?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_id.to_owned().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ cache::get_or_populate_in_memory(
+ self,
+ merchant_id.get_string_repr(),
+ fetch_func,
+ &ACCOUNTS_CACHE,
+ )
+ .await?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+ }
+
+ #[instrument(skip_all)]
+ async fn update_merchant(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantAccount,
+ merchant_account: domain::MerchantAccountUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+
+ let updated_merchant_account = Conversion::convert(this)
+ .await
+ .change_context(StorageError::EncryptionError)?
+ .update(&conn, merchant_account.into())
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?;
+ }
+ updated_merchant_account
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn update_specific_fields_in_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_account: domain::MerchantAccountUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+ let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields(
+ &conn,
+ merchant_id,
+ merchant_account.into(),
+ )
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?;
+ }
+ updated_merchant_account
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn find_merchant_account_by_publishable_key(
+ &self,
+ state: &KeyManagerState,
+ publishable_key: &str,
+ ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {
+ let fetch_by_pub_key_func = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+
+ storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ };
+
+ let merchant_account;
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ merchant_account = fetch_by_pub_key_func().await?;
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ merchant_account = cache::get_or_populate_in_memory(
+ self,
+ publishable_key,
+ fetch_by_pub_key_func,
+ &ACCOUNTS_CACHE,
+ )
+ .await?;
+ }
+ let key_store = self
+ .get_merchant_key_store_by_merchant_id(
+ state,
+ merchant_account.get_id(),
+ &self.master_key().peek().to_vec().into(),
+ )
+ .await?;
+ let domain_merchant_account = merchant_account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?;
+ Ok((domain_merchant_account, key_store))
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ state: &KeyManagerState,
+ organization_id: &common_utils::id_type::OrganizationId,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
+ use futures::future::try_join_all;
+ let conn = pg_accounts_connection_read(self).await?;
+
+ let encrypted_merchant_accounts =
+ storage::MerchantAccount::list_by_organization_id(&conn, organization_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ let db_master_key = self.master_key().peek().to_vec().into();
+
+ let merchant_key_stores =
+ try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| {
+ self.get_merchant_key_store_by_merchant_id(
+ state,
+ merchant_account.get_id(),
+ &db_master_key,
+ )
+ }))
+ .await?;
+
+ let merchant_accounts = try_join_all(
+ encrypted_merchant_accounts
+ .into_iter()
+ .zip(merchant_key_stores.iter())
+ .map(|(merchant_account, key_store)| async {
+ merchant_account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }),
+ )
+ .await?;
+
+ Ok(merchant_accounts)
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_merchant_account_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ let conn = pg_accounts_connection_write(self).await?;
+
+ let is_deleted_func = || async {
+ storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ };
+
+ let is_deleted;
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ is_deleted = is_deleted_func().await?;
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let merchant_account =
+ storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ is_deleted = is_deleted_func().await?;
+
+ publish_and_redact_merchant_account_cache(self, &merchant_account).await?;
+ }
+
+ Ok(is_deleted)
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_multiple_merchant_accounts(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
+ let conn = pg_accounts_connection_read(self).await?;
+
+ let encrypted_merchant_accounts =
+ storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ let db_master_key = self.master_key().peek().to_vec().into();
+
+ let merchant_key_stores = self
+ .list_multiple_key_stores(
+ state,
+ encrypted_merchant_accounts
+ .iter()
+ .map(|merchant_account| merchant_account.get_id())
+ .cloned()
+ .collect(),
+ &db_master_key,
+ )
+ .await?;
+
+ let key_stores_by_id: HashMap<_, _> = merchant_key_stores
+ .iter()
+ .map(|key_store| (key_store.merchant_id.to_owned(), key_store))
+ .collect();
+
+ let merchant_accounts =
+ futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map(
+ |merchant_account| async {
+ let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or(
+ StorageError::ValueNotFound(format!(
+ "merchant_key_store with merchant_id = {:?}",
+ merchant_account.get_id()
+ )),
+ )?;
+ merchant_account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ },
+ ))
+ .await?;
+
+ Ok(merchant_accounts)
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_merchant_and_org_ids(
+ &self,
+ _state: &KeyManagerState,
+ limit: u32,
+ offset: Option<u32>,
+ ) -> CustomResult<
+ Vec<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::OrganizationId,
+ )>,
+ StorageError,
+ > {
+ let conn = pg_accounts_connection_read(self).await?;
+ let encrypted_merchant_accounts =
+ storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ let merchant_and_org_ids = encrypted_merchant_accounts
+ .into_iter()
+ .map(|merchant_account| {
+ let merchant_id = merchant_account.get_id().clone();
+ let org_id = merchant_account.organization_id;
+ (merchant_id, org_id)
+ })
+ .collect();
+ Ok(merchant_and_org_ids)
+ }
+
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account: domain::MerchantAccountUpdate,
+ ) -> CustomResult<usize, StorageError> {
+ let conn = pg_accounts_connection_read(self).await?;
+
+ let db_func = || async {
+ storage::MerchantAccount::update_all_merchant_accounts(
+ &conn,
+ MerchantAccountUpdateInternal::from(merchant_account),
+ )
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ };
+
+ let total;
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ let ma = db_func().await?;
+ total = ma.len();
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let ma = db_func().await?;
+ publish_and_redact_all_merchant_account_cache(self, &ma).await?;
+ total = ma.len();
+ }
+
+ Ok(total)
+ }
+}
+
+#[async_trait::async_trait]
+impl MerchantAccountInterface for MockDb {
+ type Error = StorageError;
+ #[allow(clippy::panic)]
+ async fn insert_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_account: domain::MerchantAccount,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let mut accounts = self.merchant_accounts.lock().await;
+ let account = Conversion::convert(merchant_account)
+ .await
+ .change_context(StorageError::EncryptionError)?;
+ accounts.push(account.clone());
+
+ account
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[allow(clippy::panic)]
+ async fn find_merchant_account_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let accounts = self.merchant_accounts.lock().await;
+ accounts
+ .iter()
+ .find(|account| account.get_id() == merchant_id)
+ .cloned()
+ .ok_or(StorageError::ValueNotFound(format!(
+ "Merchant ID: {merchant_id:?} not found",
+ )))?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ async fn update_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_account: domain::MerchantAccount,
+ merchant_account_update: domain::MerchantAccountUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let merchant_id = merchant_account.get_id().to_owned();
+ let mut accounts = self.merchant_accounts.lock().await;
+ accounts
+ .iter_mut()
+ .find(|account| account.get_id() == merchant_account.get_id())
+ .async_map(|account| async {
+ let update = MerchantAccountUpdateInternal::from(merchant_account_update)
+ .apply_changeset(
+ Conversion::convert(merchant_account)
+ .await
+ .change_context(StorageError::EncryptionError)?,
+ );
+ *account = update.clone();
+ update
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",))
+ .into(),
+ )
+ }
+
+ async fn update_specific_fields_in_merchant(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_account_update: domain::MerchantAccountUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantAccount, StorageError> {
+ let mut accounts = self.merchant_accounts.lock().await;
+ accounts
+ .iter_mut()
+ .find(|account| account.get_id() == merchant_id)
+ .async_map(|account| async {
+ let update = MerchantAccountUpdateInternal::from(merchant_account_update)
+ .apply_changeset(account.clone());
+ *account = update.clone();
+ update
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",))
+ .into(),
+ )
+ }
+
+ async fn find_merchant_account_by_publishable_key(
+ &self,
+ state: &KeyManagerState,
+ publishable_key: &str,
+ ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {
+ let accounts = self.merchant_accounts.lock().await;
+ let account = accounts
+ .iter()
+ .find(|account| {
+ account
+ .publishable_key
+ .as_ref()
+ .is_some_and(|key| key == publishable_key)
+ })
+ .ok_or(StorageError::ValueNotFound(format!(
+ "Publishable Key: {publishable_key} not found",
+ )))?;
+ let key_store = self
+ .get_merchant_key_store_by_merchant_id(
+ state,
+ account.get_id(),
+ &self.get_master_key().to_vec().into(),
+ )
+ .await?;
+ let merchant_account = account
+ .clone()
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?;
+ Ok((merchant_account, key_store))
+ }
+
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account_update: domain::MerchantAccountUpdate,
+ ) -> CustomResult<usize, StorageError> {
+ let mut accounts = self.merchant_accounts.lock().await;
+ Ok(accounts.iter_mut().fold(0, |acc, account| {
+ let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone())
+ .apply_changeset(account.clone());
+ *account = update;
+ acc + 1
+ }))
+ }
+
+ async fn delete_merchant_account_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ let mut accounts = self.merchant_accounts.lock().await;
+ accounts.retain(|x| x.get_id() != merchant_id);
+ Ok(true)
+ }
+
+ #[cfg(feature = "olap")]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ state: &KeyManagerState,
+ organization_id: &common_utils::id_type::OrganizationId,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
+ let accounts = self.merchant_accounts.lock().await;
+ let futures = accounts
+ .iter()
+ .filter(|account| account.organization_id == *organization_id)
+ .map(|account| async {
+ let key_store = self
+ .get_merchant_key_store_by_merchant_id(
+ state,
+ account.get_id(),
+ &self.get_master_key().to_vec().into(),
+ )
+ .await;
+ match key_store {
+ Ok(key) => account
+ .clone()
+ .convert(state, key.key.get_inner(), key.merchant_id.clone().into())
+ .await
+ .change_context(StorageError::DecryptionError),
+ Err(err) => Err(err),
+ }
+ });
+ futures::future::join_all(futures)
+ .await
+ .into_iter()
+ .collect()
+ }
+
+ #[cfg(feature = "olap")]
+ async fn list_multiple_merchant_accounts(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
+ let accounts = self.merchant_accounts.lock().await;
+ let futures = accounts
+ .iter()
+ .filter(|account| merchant_ids.contains(account.get_id()))
+ .map(|account| async {
+ let key_store = self
+ .get_merchant_key_store_by_merchant_id(
+ state,
+ account.get_id(),
+ &self.get_master_key().to_vec().into(),
+ )
+ .await;
+ match key_store {
+ Ok(key) => account
+ .clone()
+ .convert(state, key.key.get_inner(), key.merchant_id.clone().into())
+ .await
+ .change_context(StorageError::DecryptionError),
+ Err(err) => Err(err),
+ }
+ });
+ futures::future::join_all(futures)
+ .await
+ .into_iter()
+ .collect()
+ }
+
+ #[cfg(feature = "olap")]
+ async fn list_merchant_and_org_ids(
+ &self,
+ _state: &KeyManagerState,
+ limit: u32,
+ offset: Option<u32>,
+ ) -> CustomResult<
+ Vec<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::OrganizationId,
+ )>,
+ StorageError,
+ > {
+ let accounts = self.merchant_accounts.lock().await;
+ let limit = limit.try_into().unwrap_or(accounts.len());
+ let offset = offset.unwrap_or(0).try_into().unwrap_or(0);
+
+ let merchant_and_org_ids = accounts
+ .iter()
+ .skip(offset)
+ .take(limit)
+ .map(|account| (account.get_id().clone(), account.organization_id.clone()))
+ .collect::<Vec<_>>();
+
+ Ok(merchant_and_org_ids)
+ }
+}
+
+#[cfg(feature = "accounts_cache")]
+async fn publish_and_redact_merchant_account_cache(
+ store: &(dyn RedisConnInterface + Send + Sync),
+ merchant_account: &storage::MerchantAccount,
+) -> CustomResult<(), StorageError> {
+ let publishable_key = merchant_account
+ .publishable_key
+ .as_ref()
+ .map(|publishable_key| CacheKind::Accounts(publishable_key.into()));
+
+ #[cfg(feature = "v1")]
+ let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| {
+ CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ merchant_account.get_id().get_string_repr(),
+ profile_id.get_string_repr(),
+ )
+ .into(),
+ )
+ });
+
+ // TODO: we will not have default profile in v2
+ #[cfg(feature = "v2")]
+ let cgraph_key = None;
+
+ let mut cache_keys = vec![CacheKind::Accounts(
+ merchant_account.get_id().get_string_repr().into(),
+ )];
+
+ cache_keys.extend(publishable_key.into_iter());
+ cache_keys.extend(cgraph_key.into_iter());
+
+ cache::redact_from_redis_and_publish(store, cache_keys).await?;
+ Ok(())
+}
+
+#[cfg(feature = "accounts_cache")]
+async fn publish_and_redact_all_merchant_account_cache(
+ cache: &(dyn RedisConnInterface + Send + Sync),
+ merchant_accounts: &[storage::MerchantAccount],
+) -> CustomResult<(), StorageError> {
+ let merchant_ids = merchant_accounts
+ .iter()
+ .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string());
+ let publishable_keys = merchant_accounts
+ .iter()
+ .filter_map(|m| m.publishable_key.clone());
+
+ let cache_keys: Vec<CacheKind<'_>> = merchant_ids
+ .chain(publishable_keys)
+ .map(|s| CacheKind::Accounts(s.into()))
+ .collect();
+
+ cache::redact_from_redis_and_publish(cache, cache_keys).await?;
+ Ok(())
+}
diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rs
new file mode 100644
index 0000000000..c8f09748da
--- /dev/null
+++ b/crates/storage_impl/src/merchant_connector_account.rs
@@ -0,0 +1,1531 @@
+use async_bb8_diesel::AsyncConnection;
+use common_utils::{encryption::Encryption, ext_traits::AsyncExt};
+use diesel_models::merchant_connector_account as storage;
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ behaviour::{Conversion, ReverseConversion},
+ merchant_connector_account::{self as domain, MerchantConnectorAccountInterface},
+ merchant_key_store::MerchantKeyStore,
+};
+use router_env::{instrument, tracing};
+
+#[cfg(feature = "accounts_cache")]
+use crate::redis::cache;
+use crate::{
+ kv_router_store,
+ utils::{pg_accounts_connection_read, pg_accounts_connection_write},
+ CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> MerchantConnectorAccountInterface for kv_router_store::KVRouterStore<T> {
+ type Error = StorageError;
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_merchant_id_connector_label(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector_label: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.router_store
+ .find_merchant_connector_account_by_merchant_id_connector_label(
+ state,
+ merchant_id,
+ connector_label,
+ key_store,
+ )
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.router_store
+ .find_merchant_connector_account_by_profile_id_connector_name(
+ state,
+ profile_id,
+ connector_name,
+ key_store,
+ )
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_merchant_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
+ self.router_store
+ .find_merchant_connector_account_by_merchant_id_connector_name(
+ state,
+ merchant_id,
+ connector_name,
+ key_store,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v1")]
+ async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.router_store
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ state,
+ merchant_id,
+ merchant_connector_id,
+ key_store,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn find_merchant_connector_account_by_id(
+ &self,
+ state: &KeyManagerState,
+ id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.router_store
+ .find_merchant_connector_account_by_id(state, id, key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn insert_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ t: domain::MerchantConnectorAccount,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.router_store
+ .insert_merchant_connector_account(state, t, key_store)
+ .await
+ }
+
+ async fn list_enabled_connector_accounts_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ connector_type: common_enums::ConnectorType,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
+ self.router_store
+ .list_enabled_connector_accounts_by_profile_id(
+ state,
+ profile_id,
+ key_store,
+ connector_type,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ get_disabled: bool,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> {
+ self.router_store
+ .find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ state,
+ merchant_id,
+ get_disabled,
+ key_store,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(all(feature = "olap", feature = "v2"))]
+ async fn list_connector_account_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
+ self.router_store
+ .list_connector_account_by_profile_id(state, profile_id, key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), Self::Error> {
+ self.router_store
+ .update_multiple_merchant_connector_accounts(merchant_connector_accounts)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v1")]
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantConnectorAccount,
+ merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.router_store
+ .update_merchant_connector_account(state, this, merchant_connector_account, key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantConnectorAccount,
+ merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ self.update_merchant_connector_account(state, this, merchant_connector_account, key_store)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v1")]
+ async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, Self::Error> {
+ self.router_store
+ .delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
+ merchant_id,
+ merchant_connector_id,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn delete_merchant_connector_account_by_id(
+ &self,
+ id: &common_utils::id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, Self::Error> {
+ self.router_store
+ .delete_merchant_connector_account_by_id(id)
+ .await
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
+ type Error = StorageError;
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_merchant_id_connector_label(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector_label: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let find_call = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantConnectorAccount::find_by_merchant_id_connector(
+ &conn,
+ merchant_id,
+ connector_label,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ find_call()
+ .await?
+ .convert(state, key_store.key.get_inner(), merchant_id.clone().into())
+ .await
+ .change_context(Self::Error::DeserializationFailed)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ cache::get_or_populate_in_memory(
+ self,
+ &format!("{}_{}", merchant_id.get_string_repr(), connector_label),
+ find_call,
+ &cache::ACCOUNTS_CACHE,
+ )
+ .await
+ .async_and_then(|item| async {
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ })
+ .await
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let find_call = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantConnectorAccount::find_by_profile_id_connector_name(
+ &conn,
+ profile_id,
+ connector_name,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ find_call()
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DeserializationFailed)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ cache::get_or_populate_in_memory(
+ self,
+ &format!("{}_{}", profile_id.get_string_repr(), connector_name),
+ find_call,
+ &cache::ACCOUNTS_CACHE,
+ )
+ .await
+ .async_and_then(|item| async {
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ })
+ .await
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_merchant_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantConnectorAccount::find_by_merchant_id_connector_name(
+ &conn,
+ merchant_id,
+ connector_name,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|items| async {
+ let mut output = Vec::with_capacity(items.len());
+ for item in items.into_iter() {
+ output.push(
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)?,
+ )
+ }
+ Ok(output)
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v1")]
+ async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let find_call = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(
+ &conn,
+ merchant_id,
+ merchant_connector_id,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ find_call()
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ cache::get_or_populate_in_memory(
+ self,
+ &format!(
+ "{}_{}",
+ merchant_id.get_string_repr(),
+ merchant_connector_id.get_string_repr()
+ ),
+ find_call,
+ &cache::ACCOUNTS_CACHE,
+ )
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn find_merchant_connector_account_by_id(
+ &self,
+ state: &KeyManagerState,
+ id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let find_call = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantConnectorAccount::find_by_id(&conn, id)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ find_call()
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ cache::get_or_populate_in_memory(
+ self,
+ id.get_string_repr(),
+ find_call,
+ &cache::ACCOUNTS_CACHE,
+ )
+ .await?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ key_store.merchant_id.clone(),
+ ),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+ }
+
+ #[instrument(skip_all)]
+ async fn insert_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ t: domain::MerchantConnectorAccount,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let conn = pg_accounts_connection_write(self).await?;
+ t.construct_new()
+ .await
+ .change_context(Self::Error::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|item| async {
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ })
+ .await
+ }
+
+ async fn list_enabled_connector_accounts_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ connector_type: common_enums::ConnectorType,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
+ let conn = pg_accounts_connection_read(self).await?;
+
+ storage::MerchantConnectorAccount::list_enabled_by_profile_id(
+ &conn,
+ profile_id,
+ connector_type,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|items| async {
+ let mut output = Vec::with_capacity(items.len());
+ for item in items.into_iter() {
+ output.push(
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)?,
+ )
+ }
+ Ok(output)
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ get_disabled: bool,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> {
+ let conn = pg_accounts_connection_read(self).await?;
+ let merchant_connector_account_vec =
+ storage::MerchantConnectorAccount::find_by_merchant_id(
+ &conn,
+ merchant_id,
+ get_disabled,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|items| async {
+ let mut output = Vec::with_capacity(items.len());
+ for item in items.into_iter() {
+ output.push(
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)?,
+ )
+ }
+ Ok(output)
+ })
+ .await?;
+ Ok(domain::MerchantConnectorAccounts::new(
+ merchant_connector_account_vec,
+ ))
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(all(feature = "olap", feature = "v2"))]
+ async fn list_connector_account_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
+ let conn = pg_accounts_connection_read(self).await?;
+ storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|items| async {
+ let mut output = Vec::with_capacity(items.len());
+ for item in items.into_iter() {
+ output.push(
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)?,
+ )
+ }
+ Ok(output)
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), Self::Error> {
+ let conn = pg_accounts_connection_write(self).await?;
+
+ async fn update_call(
+ connection: &diesel_models::PgPooledConn,
+ (merchant_connector_account, mca_update): (
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ ),
+ ) -> Result<(), error_stack::Report<StorageError>> {
+ Conversion::convert(merchant_connector_account)
+ .await
+ .change_context(StorageError::EncryptionError)?
+ .update(connection, mca_update)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+ Ok(())
+ }
+
+ conn.transaction_async(|connection_pool| async move {
+ for (merchant_connector_account, update_merchant_connector_account) in
+ merchant_connector_accounts
+ {
+ #[cfg(feature = "v1")]
+ let _connector_name = merchant_connector_account.connector_name.clone();
+
+ #[cfg(feature = "v2")]
+ let _connector_name = merchant_connector_account.connector_name.to_string();
+
+ let _profile_id = merchant_connector_account.profile_id.clone();
+
+ let _merchant_id = merchant_connector_account.merchant_id.clone();
+ let _merchant_connector_id = merchant_connector_account.get_id().clone();
+
+ let update = update_call(
+ &connection_pool,
+ (
+ merchant_connector_account,
+ update_merchant_connector_account,
+ ),
+ );
+
+ #[cfg(feature = "accounts_cache")]
+ // Redact all caches as any of might be used because of backwards compatibility
+ Box::pin(cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
+ ),
+ cache::CacheKind::Accounts(
+ format!(
+ "{}_{}",
+ _merchant_id.get_string_repr(),
+ _merchant_connector_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ _merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ ],
+ || update,
+ ))
+ .await
+ .map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ Self::Error::DatabaseConnectionError
+ })?;
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ update.await.map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ Self::Error::DatabaseConnectionError
+ })?;
+ }
+ }
+ Ok::<_, Self::Error>(())
+ })
+ .await?;
+ Ok(())
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v1")]
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantConnectorAccount,
+ merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let _connector_name = this.connector_name.clone();
+ let _profile_id = this.profile_id.clone();
+
+ let _merchant_id = this.merchant_id.clone();
+ let _merchant_connector_id = this.merchant_connector_id.clone();
+
+ let update_call = || async {
+ let conn = pg_accounts_connection_write(self).await?;
+ Conversion::convert(this)
+ .await
+ .change_context(Self::Error::EncryptionError)?
+ .update(&conn, merchant_connector_account)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|item| async {
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ })
+ .await
+ };
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ // Redact all caches as any of might be used because of backwards compatibility
+ cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
+ ),
+ cache::CacheKind::Accounts(
+ format!(
+ "{}_{}",
+ _merchant_id.get_string_repr(),
+ _merchant_connector_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ _merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::PmFiltersCGraph(
+ format!(
+ "pm_filters_cgraph_{}_{}",
+ _merchant_id.get_string_repr(),
+ _profile_id.get_string_repr(),
+ )
+ .into(),
+ ),
+ ],
+ update_call,
+ )
+ .await
+ }
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ update_call().await
+ }
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantConnectorAccount,
+ merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
+ let _connector_name = this.connector_name;
+ let _profile_id = this.profile_id.clone();
+
+ let _merchant_id = this.merchant_id.clone();
+ let _merchant_connector_id = this.get_id().clone();
+
+ let update_call = || async {
+ let conn = pg_accounts_connection_write(self).await?;
+ Conversion::convert(this)
+ .await
+ .change_context(Self::Error::EncryptionError)?
+ .update(&conn, merchant_connector_account)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ .async_and_then(|item| async {
+ item.convert(
+ state,
+ key_store.key.get_inner(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ key_store.merchant_id.clone(),
+ ),
+ )
+ .await
+ .change_context(Self::Error::DecryptionError)
+ })
+ .await
+ };
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ // Redact all caches as any of might be used because of backwards compatibility
+ cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
+ ),
+ cache::CacheKind::Accounts(
+ _merchant_connector_id.get_string_repr().to_string().into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ _merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::PmFiltersCGraph(
+ format!(
+ "pm_filters_cgraph_{}_{}",
+ _merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ ],
+ update_call,
+ )
+ .await
+ }
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ update_call().await
+ }
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v1")]
+ async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, Self::Error> {
+ let conn = pg_accounts_connection_write(self).await?;
+ let delete_call = || async {
+ storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id(
+ &conn,
+ merchant_id,
+ merchant_connector_id,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ // We need to fetch mca here because the key that's saved in cache in
+ // {merchant_id}_{connector_label}.
+ // Used function from storage model to reuse the connection that made here instead of
+ // creating new.
+
+ let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(
+ &conn,
+ merchant_id,
+ merchant_connector_id,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))?;
+
+ let _profile_id = mca
+ .profile_id
+ .ok_or(Self::Error::ValueNotFound("profile_id".to_string()))?;
+
+ cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!(
+ "{}_{}",
+ mca.merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ mca.merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::PmFiltersCGraph(
+ format!(
+ "pm_filters_cgraph_{}_{}",
+ mca.merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ ],
+ delete_call,
+ )
+ .await
+ }
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ delete_call().await
+ }
+ }
+
+ #[instrument(skip_all)]
+ #[cfg(feature = "v2")]
+ async fn delete_merchant_connector_account_by_id(
+ &self,
+ id: &common_utils::id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, Self::Error> {
+ let conn = pg_accounts_connection_write(self).await?;
+ let delete_call = || async {
+ storage::MerchantConnectorAccount::delete_by_id(&conn, id)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ // We need to fetch mca here because the key that's saved in cache in
+ // {merchant_id}_{connector_label}.
+ // Used function from storage model to reuse the connection that made here instead of
+ // creating new.
+
+ let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))?;
+
+ let _profile_id = mca.profile_id;
+
+ cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!(
+ "{}_{}",
+ mca.merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ mca.merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::PmFiltersCGraph(
+ format!(
+ "pm_filters_cgraph_{}_{}",
+ mca.merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ ],
+ delete_call,
+ )
+ .await
+ }
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ delete_call().await
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl MerchantConnectorAccountInterface for MockDb {
+ type Error = StorageError;
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ _merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), StorageError> {
+ // No need to implement this function for `MockDb` as this function will be removed after the
+ // apple pay certificate migration
+ Err(StorageError::MockDbError)?
+ }
+ #[cfg(feature = "v1")]
+ async fn find_merchant_connector_account_by_merchant_id_connector_label(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ match self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .find(|account| {
+ account.merchant_id == *merchant_id
+ && account.connector_label == Some(connector.to_string())
+ })
+ .cloned()
+ .async_map(|account| async {
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ {
+ Some(result) => result,
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+
+ async fn list_enabled_connector_accounts_by_profile_id(
+ &self,
+ _state: &KeyManagerState,
+ _profile_id: &common_utils::id_type::ProfileId,
+ _key_store: &MerchantKeyStore,
+ _connector_type: common_enums::ConnectorType,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
+
+ #[cfg(feature = "v1")]
+ async fn find_merchant_connector_account_by_merchant_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> {
+ let accounts = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .filter(|account| {
+ account.merchant_id == *merchant_id && account.connector_name == connector_name
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+ let mut output = Vec::with_capacity(accounts.len());
+ for account in accounts.into_iter() {
+ output.push(
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?,
+ )
+ }
+ Ok(output)
+ }
+
+ #[cfg(feature = "v1")]
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_name: &str,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ let maybe_mca = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .find(|account| {
+ account.profile_id.eq(&Some(profile_id.to_owned()))
+ && account.connector_name == connector_name
+ })
+ .cloned();
+
+ match maybe_mca {
+ Some(mca) => mca
+ .to_owned()
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError),
+ None => Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account".to_string(),
+ )
+ .into()),
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ match self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .find(|account| {
+ account.merchant_id == *merchant_id
+ && account.merchant_connector_id == *merchant_connector_id
+ })
+ .cloned()
+ .async_map(|account| async {
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ {
+ Some(result) => result,
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ async fn find_merchant_connector_account_by_id(
+ &self,
+ state: &KeyManagerState,
+ id: &common_utils::id_type::MerchantConnectorAccountId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ match self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .find(|account| account.get_id() == *id)
+ .cloned()
+ .async_map(|account| async {
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ key_store.merchant_id.clone(),
+ ),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await
+ {
+ Some(result) => result,
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ async fn insert_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ t: domain::MerchantConnectorAccount,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ let mut accounts = self.merchant_connector_accounts.lock().await;
+ let account = storage::MerchantConnectorAccount {
+ merchant_id: t.merchant_id,
+ connector_name: t.connector_name,
+ connector_account_details: t.connector_account_details.into(),
+ test_mode: t.test_mode,
+ disabled: t.disabled,
+ merchant_connector_id: t.merchant_connector_id.clone(),
+ id: Some(t.merchant_connector_id),
+ payment_methods_enabled: t.payment_methods_enabled,
+ metadata: t.metadata,
+ frm_configs: None,
+ frm_config: t.frm_configs,
+ connector_type: t.connector_type,
+ connector_label: t.connector_label,
+ business_country: t.business_country,
+ business_label: t.business_label,
+ business_sub_label: t.business_sub_label,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ connector_webhook_details: t.connector_webhook_details,
+ profile_id: Some(t.profile_id),
+ applepay_verified_domains: t.applepay_verified_domains,
+ pm_auth_config: t.pm_auth_config,
+ status: t.status,
+ connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
+ version: t.version,
+ };
+ accounts.push(account.clone());
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[cfg(feature = "v2")]
+ async fn insert_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ t: domain::MerchantConnectorAccount,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ let mut accounts = self.merchant_connector_accounts.lock().await;
+ let account = storage::MerchantConnectorAccount {
+ id: t.id,
+ merchant_id: t.merchant_id,
+ connector_name: t.connector_name,
+ connector_account_details: t.connector_account_details.into(),
+ disabled: t.disabled,
+ payment_methods_enabled: t.payment_methods_enabled,
+ metadata: t.metadata,
+ frm_config: t.frm_configs,
+ connector_type: t.connector_type,
+ connector_label: t.connector_label,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ connector_webhook_details: t.connector_webhook_details,
+ profile_id: t.profile_id,
+ applepay_verified_domains: t.applepay_verified_domains,
+ pm_auth_config: t.pm_auth_config,
+ status: t.status,
+ connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
+ version: t.version,
+ feature_metadata: t.feature_metadata.map(From::from),
+ };
+ accounts.push(account.clone());
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ key_store.merchant_id.clone(),
+ ),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ get_disabled: bool,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccounts, StorageError> {
+ let accounts = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .filter(|account: &&storage::MerchantConnectorAccount| {
+ if get_disabled {
+ account.merchant_id == *merchant_id
+ } else {
+ account.merchant_id == *merchant_id && account.disabled == Some(false)
+ }
+ })
+ .cloned()
+ .collect::<Vec<storage::MerchantConnectorAccount>>();
+
+ let mut output = Vec::with_capacity(accounts.len());
+ for account in accounts.into_iter() {
+ output.push(
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?,
+ )
+ }
+ Ok(domain::MerchantConnectorAccounts::new(output))
+ }
+
+ #[cfg(all(feature = "olap", feature = "v2"))]
+ async fn list_connector_account_by_profile_id(
+ &self,
+ state: &KeyManagerState,
+ profile_id: &common_utils::id_type::ProfileId,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> {
+ let accounts = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .filter(|account: &&storage::MerchantConnectorAccount| {
+ account.profile_id == *profile_id
+ })
+ .cloned()
+ .collect::<Vec<storage::MerchantConnectorAccount>>();
+
+ let mut output = Vec::with_capacity(accounts.len());
+ for account in accounts.into_iter() {
+ output.push(
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?,
+ )
+ }
+ Ok(output)
+ }
+
+ #[cfg(feature = "v1")]
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantConnectorAccount,
+ merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ let mca_update_res = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter_mut()
+ .find(|account| account.merchant_connector_id == this.merchant_connector_id)
+ .map(|a| {
+ let updated =
+ merchant_connector_account.create_merchant_connector_account(a.clone());
+ *a = updated.clone();
+ updated
+ })
+ .async_map(|account| async {
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await;
+
+ match mca_update_res {
+ Some(result) => result,
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account to update".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ async fn update_merchant_connector_account(
+ &self,
+ state: &KeyManagerState,
+ this: domain::MerchantConnectorAccount,
+ merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
+ key_store: &MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
+ let mca_update_res = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter_mut()
+ .find(|account| account.get_id() == this.get_id())
+ .map(|a| {
+ let updated =
+ merchant_connector_account.create_merchant_connector_account(a.clone());
+ *a = updated.clone();
+ updated
+ })
+ .async_map(|account| async {
+ account
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ key_store.merchant_id.clone(),
+ ),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ })
+ .await;
+
+ match mca_update_res {
+ Some(result) => result,
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account to update".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, StorageError> {
+ let mut accounts = self.merchant_connector_accounts.lock().await;
+ match accounts.iter().position(|account| {
+ account.merchant_id == *merchant_id
+ && account.merchant_connector_id == *merchant_connector_id
+ }) {
+ Some(index) => {
+ accounts.remove(index);
+ return Ok(true);
+ }
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account to delete".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ async fn delete_merchant_connector_account_by_id(
+ &self,
+ id: &common_utils::id_type::MerchantConnectorAccountId,
+ ) -> CustomResult<bool, StorageError> {
+ let mut accounts = self.merchant_connector_accounts.lock().await;
+ match accounts.iter().position(|account| account.get_id() == *id) {
+ Some(index) => {
+ accounts.remove(index);
+ return Ok(true);
+ }
+ None => {
+ return Err(StorageError::ValueNotFound(
+ "cannot find merchant connector account to delete".to_string(),
+ )
+ .into())
+ }
+ }
+ }
+}
diff --git a/crates/storage_impl/src/merchant_key_store.rs b/crates/storage_impl/src/merchant_key_store.rs
new file mode 100644
index 0000000000..36126460af
--- /dev/null
+++ b/crates/storage_impl/src/merchant_key_store.rs
@@ -0,0 +1,346 @@
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ behaviour::{Conversion, ReverseConversion},
+ merchant_key_store as domain,
+ merchant_key_store::MerchantKeyStoreInterface,
+};
+use masking::Secret;
+use router_env::{instrument, tracing};
+
+#[cfg(feature = "accounts_cache")]
+use crate::redis::{
+ cache,
+ cache::{CacheKind, ACCOUNTS_CACHE},
+};
+use crate::{
+ kv_router_store,
+ utils::{pg_accounts_connection_read, pg_accounts_connection_write},
+ CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> MerchantKeyStoreInterface for kv_router_store::KVRouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_merchant_key_store(
+ &self,
+ state: &KeyManagerState,
+ merchant_key_store: domain::MerchantKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
+ self.router_store
+ .insert_merchant_key_store(state, merchant_key_store, key)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn get_merchant_key_store_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
+ self.router_store
+ .get_merchant_key_store_by_merchant_id(state, merchant_id, key)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_merchant_key_store_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, Self::Error> {
+ self.router_store
+ .delete_merchant_key_store_by_merchant_id(merchant_id)
+ .await
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_multiple_key_stores(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
+ self.router_store
+ .list_multiple_key_stores(state, merchant_ids, key)
+ .await
+ }
+
+ async fn get_all_key_stores(
+ &self,
+ state: &KeyManagerState,
+ key: &Secret<Vec<u8>>,
+ from: u32,
+ to: u32,
+ ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
+ self.router_store
+ .get_all_key_stores(state, key, from, to)
+ .await
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {
+ type Error = StorageError;
+ #[instrument(skip_all)]
+ async fn insert_merchant_key_store(
+ &self,
+ state: &KeyManagerState,
+ merchant_key_store: domain::MerchantKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
+ let conn = pg_accounts_connection_write(self).await?;
+ let merchant_id = merchant_key_store.merchant_id.clone();
+ merchant_key_store
+ .construct_new()
+ .await
+ .change_context(Self::Error::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))?
+ .convert(state, key, merchant_id.into())
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_merchant_key_store_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
+ let fetch_func = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+
+ diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id(
+ &conn,
+ merchant_id,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ fetch_func()
+ .await?
+ .convert(state, key, merchant_id.clone().into())
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let key_store_cache_key =
+ format!("merchant_key_store_{}", merchant_id.get_string_repr());
+ cache::get_or_populate_in_memory(
+ self,
+ &key_store_cache_key,
+ fetch_func,
+ &ACCOUNTS_CACHE,
+ )
+ .await?
+ .convert(state, key, merchant_id.clone().into())
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_merchant_key_store_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, Self::Error> {
+ let delete_func = || async {
+ let conn = pg_accounts_connection_write(self).await?;
+ diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id(
+ &conn,
+ merchant_id,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ delete_func().await
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let key_store_cache_key =
+ format!("merchant_key_store_{}", merchant_id.get_string_repr());
+ cache::publish_and_redact(
+ self,
+ CacheKind::Accounts(key_store_cache_key.into()),
+ delete_func,
+ )
+ .await
+ }
+ }
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn list_multiple_key_stores(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
+ let fetch_func = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+
+ diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores(
+ &conn,
+ merchant_ids,
+ )
+ .await
+ .map_err(|error| report!(Self::Error::from(error)))
+ };
+
+ futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async {
+ let merchant_id = key_store.merchant_id.clone();
+ key_store
+ .convert(state, key, merchant_id.into())
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }))
+ .await
+ }
+
+ async fn get_all_key_stores(
+ &self,
+ state: &KeyManagerState,
+ key: &Secret<Vec<u8>>,
+ from: u32,
+ to: u32,
+ ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
+ let conn = pg_accounts_connection_read(self).await?;
+ let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(
+ &conn, from, to,
+ )
+ .await
+ .map_err(|err| report!(Self::Error::from(err)))?;
+
+ futures::future::try_join_all(stores.into_iter().map(|key_store| async {
+ let merchant_id = key_store.merchant_id.clone();
+ key_store
+ .convert(state, key, merchant_id.into())
+ .await
+ .change_context(Self::Error::DecryptionError)
+ }))
+ .await
+ }
+}
+
+#[async_trait::async_trait]
+impl MerchantKeyStoreInterface for MockDb {
+ type Error = StorageError;
+ async fn insert_merchant_key_store(
+ &self,
+ state: &KeyManagerState,
+ merchant_key_store: domain::MerchantKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
+ let mut locked_merchant_key_store = self.merchant_key_store.lock().await;
+
+ if locked_merchant_key_store
+ .iter()
+ .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id)
+ {
+ Err(StorageError::DuplicateValue {
+ entity: "merchant_key_store",
+ key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()),
+ })?;
+ }
+
+ let merchant_key = Conversion::convert(merchant_key_store)
+ .await
+ .change_context(StorageError::MockDbError)?;
+ locked_merchant_key_store.push(merchant_key.clone());
+ let merchant_id = merchant_key.merchant_id.clone();
+ merchant_key
+ .convert(state, key, merchant_id.into())
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ async fn get_merchant_key_store_by_merchant_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::MerchantKeyStore, StorageError> {
+ self.merchant_key_store
+ .lock()
+ .await
+ .iter()
+ .find(|merchant_key| merchant_key.merchant_id == *merchant_id)
+ .cloned()
+ .ok_or(StorageError::ValueNotFound(String::from(
+ "merchant_key_store",
+ )))?
+ .convert(state, key, merchant_id.clone().into())
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ async fn delete_merchant_key_store_by_merchant_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<bool, StorageError> {
+ let mut merchant_key_stores = self.merchant_key_store.lock().await;
+ let index = merchant_key_stores
+ .iter()
+ .position(|mks| mks.merchant_id == *merchant_id)
+ .ok_or(StorageError::ValueNotFound(format!(
+ "No merchant key store found for merchant_id = {merchant_id:?}",
+ )))?;
+ merchant_key_stores.remove(index);
+ Ok(true)
+ }
+
+ #[cfg(feature = "olap")]
+ async fn list_multiple_key_stores(
+ &self,
+ state: &KeyManagerState,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> {
+ let merchant_key_stores = self.merchant_key_store.lock().await;
+ futures::future::try_join_all(
+ merchant_key_stores
+ .iter()
+ .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id))
+ .map(|merchant_key| async {
+ merchant_key
+ .to_owned()
+ .convert(state, key, merchant_key.merchant_id.clone().into())
+ .await
+ .change_context(StorageError::DecryptionError)
+ }),
+ )
+ .await
+ }
+ async fn get_all_key_stores(
+ &self,
+ state: &KeyManagerState,
+ key: &Secret<Vec<u8>>,
+ _from: u32,
+ _to: u32,
+ ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> {
+ let merchant_key_stores = self.merchant_key_store.lock().await;
+
+ futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async {
+ merchant_key
+ .to_owned()
+ .convert(state, key, merchant_key.merchant_id.clone().into())
+ .await
+ .change_context(StorageError::DecryptionError)
+ }))
+ .await
+ }
+}
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index b3fc53fb8c..8b40907cb0 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -231,6 +231,13 @@ impl MockDb {
Err(StorageError::ValueNotFound(error_message).into())
}
}
+
+ pub fn get_master_key(&self) -> &[u8] {
+ &[
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32,
+ ]
+ }
}
#[cfg(not(feature = "payouts"))]
diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rs
index fd611911d6..acd708e617 100644
--- a/crates/storage_impl/src/utils.rs
+++ b/crates/storage_impl/src/utils.rs
@@ -47,6 +47,46 @@ pub async fn pg_connection_write<T: DatabaseStore>(
.change_context(StorageError::DatabaseConnectionError)
}
+pub async fn pg_accounts_connection_read<T: DatabaseStore>(
+ store: &T,
+) -> error_stack::Result<
+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
+ StorageError,
+> {
+ // If only OLAP is enabled get replica pool.
+ #[cfg(all(feature = "olap", not(feature = "oltp")))]
+ let pool = store.get_accounts_replica_pool();
+
+ // If either one of these are true we need to get master pool.
+ // 1. Only OLTP is enabled.
+ // 2. Both OLAP and OLTP is enabled.
+ // 3. Both OLAP and OLTP is disabled.
+ #[cfg(any(
+ all(not(feature = "olap"), feature = "oltp"),
+ all(feature = "olap", feature = "oltp"),
+ all(not(feature = "olap"), not(feature = "oltp"))
+ ))]
+ let pool = store.get_accounts_master_pool();
+
+ pool.get()
+ .await
+ .change_context(StorageError::DatabaseConnectionError)
+}
+
+pub async fn pg_accounts_connection_write<T: DatabaseStore>(
+ store: &T,
+) -> error_stack::Result<
+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
+ StorageError,
+> {
+ // Since all writes should happen to master DB only choose master DB.
+ let pool = store.get_accounts_master_pool();
+
+ pool.get()
+ .await
+ .change_context(StorageError::DatabaseConnectionError)
+}
+
pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(
redis_fut: RFut,
database_call_closure: F,