Skip to content

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

feat(customer): Customer kv impl (#4267)

akshay-97c980f0169181
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index bda7af157d..fcabc8879b 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -4,7 +4,9 @@ use time::PrimitiveDateTime;
use crate::{encryption::Encryption, schema::customers};
-#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
+#[derive(
+ Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
+)]
#[diesel(table_name = customers)]
pub struct CustomerNew {
pub customer_id: String,
@@ -21,7 +23,28 @@ pub struct CustomerNew {
pub address_id: Option<String>,
}
-#[derive(Clone, Debug, Identifiable, Queryable)]
+impl From<CustomerNew> for Customer {
+ fn from(customer_new: CustomerNew) -> Self {
+ Self {
+ id: 0i32,
+ customer_id: customer_new.customer_id,
+ merchant_id: customer_new.merchant_id,
+ name: customer_new.name,
+ email: customer_new.email,
+ phone: customer_new.phone,
+ phone_country_code: customer_new.phone_country_code,
+ description: customer_new.description,
+ created_at: customer_new.created_at,
+ metadata: customer_new.metadata,
+ connector_customer: customer_new.connector_customer,
+ modified_at: customer_new.modified_at,
+ address_id: customer_new.address_id,
+ default_payment_method_id: None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Identifiable, Queryable, serde::Deserialize, serde::Serialize)]
#[diesel(table_name = customers)]
pub struct Customer {
pub id: i32,
@@ -40,7 +63,15 @@ pub struct Customer {
pub default_payment_method_id: Option<String>,
}
-#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
+#[derive(
+ Clone,
+ Debug,
+ Default,
+ AsChangeset,
+ router_derive::DebugAsDisplay,
+ serde::Deserialize,
+ serde::Serialize,
+)]
#[diesel(table_name = customers)]
pub struct CustomerUpdateInternal {
pub name: Option<Encryption>,
@@ -54,3 +85,36 @@ pub struct CustomerUpdateInternal {
pub address_id: Option<String>,
pub default_payment_method_id: Option<Option<String>>,
}
+
+impl CustomerUpdateInternal {
+ pub fn apply_changeset(self, source: Customer) -> Customer {
+ let Self {
+ name,
+ email,
+ phone,
+ description,
+ phone_country_code,
+ metadata,
+ connector_customer,
+ address_id,
+ default_payment_method_id,
+ ..
+ } = self;
+
+ Customer {
+ name: name.map_or(source.name, Some),
+ email: email.map_or(source.email, Some),
+ phone: phone.map_or(source.phone, Some),
+ description: description.map_or(source.description, Some),
+ phone_country_code: phone_country_code.map_or(source.phone_country_code, Some),
+ metadata: metadata.map_or(source.metadata, Some),
+ modified_at: common_utils::date_time::now(),
+ connector_customer: connector_customer.map_or(source.connector_customer, Some),
+ address_id: address_id.map_or(source.address_id, Some),
+ default_payment_method_id: default_payment_method_id
+ .flatten()
+ .map_or(source.default_payment_method_id, Some),
+ ..source
+ }
+ }
+}
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index 4d0eb48259..e70216c6f3 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use crate::{
address::{Address, AddressNew, AddressUpdateInternal},
+ customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
@@ -36,6 +37,7 @@ impl DBOperation {
Insertable::Address(_) => "address",
Insertable::Payouts(_) => "payouts",
Insertable::PayoutAttempt(_) => "payout_attempt",
+ Insertable::Customer(_) => "customer",
Insertable::ReverseLookUp(_) => "reverse_lookup",
Insertable::PaymentMethod(_) => "payment_method",
},
@@ -43,6 +45,7 @@ impl DBOperation {
Updateable::PaymentIntentUpdate(_) => "payment_intent",
Updateable::PaymentAttemptUpdate(_) => "payment_attempt",
Updateable::RefundUpdate(_) => "refund",
+ Updateable::CustomerUpdate(_) => "customer",
Updateable::AddressUpdate(_) => "address",
Updateable::PayoutsUpdate(_) => "payouts",
Updateable::PayoutAttemptUpdate(_) => "payout_attempt",
@@ -58,6 +61,7 @@ pub enum DBResult {
PaymentAttempt(Box<PaymentAttempt>),
Refund(Box<Refund>),
Address(Box<Address>),
+ Customer(Box<Customer>),
ReverseLookUp(Box<ReverseLookup>),
Payouts(Box<Payouts>),
PayoutAttempt(Box<PayoutAttempt>),
@@ -82,6 +86,9 @@ impl DBOperation {
}
Insertable::Refund(a) => DBResult::Refund(Box::new(a.insert(conn).await?)),
Insertable::Address(addr) => DBResult::Address(Box::new(addr.insert(conn).await?)),
+ Insertable::Customer(cust) => {
+ DBResult::Customer(Box::new(cust.insert(conn).await?))
+ }
Insertable::ReverseLookUp(rev) => {
DBResult::ReverseLookUp(Box::new(rev.insert(conn).await?))
}
@@ -117,6 +124,15 @@ impl DBOperation {
.update_with_payment_method_id(conn, v.update_data)
.await?,
)),
+ Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new(
+ Customer::update_by_customer_id_merchant_id(
+ conn,
+ cust.orig.customer_id.clone(),
+ cust.orig.merchant_id.clone(),
+ cust.update_data,
+ )
+ .await?,
+ )),
},
})
}
@@ -150,6 +166,7 @@ pub enum Insertable {
PaymentAttempt(PaymentAttemptNew),
Refund(RefundNew),
Address(Box<AddressNew>),
+ Customer(CustomerNew),
ReverseLookUp(ReverseLookupNew),
Payouts(PayoutsNew),
PayoutAttempt(PayoutAttemptNew),
@@ -162,12 +179,19 @@ pub enum Updateable {
PaymentIntentUpdate(PaymentIntentUpdateMems),
PaymentAttemptUpdate(PaymentAttemptUpdateMems),
RefundUpdate(RefundUpdateMems),
+ CustomerUpdate(CustomerUpdateMems),
AddressUpdate(Box<AddressUpdateMems>),
PayoutsUpdate(PayoutsUpdateMems),
PayoutAttemptUpdate(PayoutAttemptUpdateMems),
PaymentMethodUpdate(PaymentMethodUpdateMems),
}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct CustomerUpdateMems {
+ pub orig: Customer,
+ pub update_data: CustomerUpdateInternal,
+}
+
#[derive(Debug, Serialize, Deserialize)]
pub struct AddressUpdateMems {
pub orig: Address,
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 4ad62c5a07..c38167f07c 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -45,7 +45,12 @@ pub async fn create_customer(
// Consider a scenario where the address is inserted and then when inserting the customer,
// it errors out, now the address that was inserted is not deleted
match db
- .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, &key_store)
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ merchant_id,
+ &key_store,
+ merchant_account.storage_scheme,
+ )
.await
{
Err(err) => {
@@ -118,7 +123,7 @@ pub async fn create_customer(
.attach_printable("Failed while encrypting Customer")?;
let customer = db
- .insert_customer(new_customer, &key_store)
+ .insert_customer(new_customer, &key_store, merchant_account.storage_scheme)
.await
.to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?;
@@ -142,6 +147,7 @@ pub async fn retrieve_customer(
&req.customer_id,
&merchant_account.merchant_id,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.switch()?;
@@ -188,13 +194,15 @@ pub async fn delete_customer(
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let db = &state.store;
- db.find_customer_by_customer_id_merchant_id(
- &req.customer_id,
- &merchant_account.merchant_id,
- &key_store,
- )
- .await
- .switch()?;
+ let customer_orig = db
+ .find_customer_by_customer_id_merchant_id(
+ &req.customer_id,
+ &merchant_account.merchant_id,
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .switch()?;
let customer_mandates = db
.find_mandate_by_merchant_id_customer_id(&merchant_account.merchant_id, &req.customer_id)
@@ -313,8 +321,10 @@ pub async fn delete_customer(
db.update_customer_by_customer_id_merchant_id(
req.customer_id.clone(),
merchant_account.merchant_id,
+ customer_orig,
updated_customer,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.switch()?;
@@ -343,6 +353,7 @@ pub async fn update_customer(
&update_customer.customer_id,
&merchant_account.merchant_id,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.switch()?;
@@ -350,7 +361,7 @@ pub async fn update_customer(
let key = key_store.key.get_inner().peek();
let address = if let Some(addr) = &update_customer.address {
- match customer.address_id {
+ match customer.address_id.clone() {
Some(address_id) => {
let customer_address: api_models::payments::AddressDetails = addr.clone();
let update_address = update_customer
@@ -359,7 +370,7 @@ pub async fn update_customer(
.switch()
.attach_printable("Failed while encrypting Address while Update")?;
Some(
- db.update_address(address_id.clone(), update_address, &key_store)
+ db.update_address(address_id, update_address, &key_store)
.await
.switch()
.attach_printable(format!(
@@ -405,6 +416,7 @@ pub async fn update_customer(
.update_customer_by_customer_id_merchant_id(
update_customer.customer_id.to_owned(),
merchant_account.merchant_id.to_owned(),
+ customer,
async {
Ok(storage::CustomerUpdate::Update {
name: update_customer
@@ -434,6 +446,7 @@ pub async fn update_customer(
.switch()
.attach_printable("Failed while encrypting while updating customer")?,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.switch()?;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 1495b2ba24..c885a3bf22 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -92,7 +92,12 @@ pub async fn create_payment_method(
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
let customer = db
- .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store)
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
@@ -1288,6 +1293,7 @@ pub async fn list_payment_methods(
cust.as_str(),
&pi.merchant_id,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
@@ -2802,6 +2808,7 @@ pub async fn list_customer_payment_method(
customer_id,
&merchant_account.merchant_id,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
@@ -3258,7 +3265,12 @@ pub async fn set_default_payment_method(
) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> {
//check for the customer
let customer = db
- .find_customer_by_customer_id_merchant_id(customer_id, &merchant_id, &key_store)
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ &merchant_id,
+ &key_store,
+ storage_scheme,
+ )
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
// check for the presence of payment_method
@@ -3289,20 +3301,24 @@ pub async fn set_default_payment_method(
default_payment_method_id: Some(Some(payment_method_id.to_owned())),
};
+ let customer_id = customer.customer_id.clone();
+
// update the db with the default payment method id
let updated_customer_details = db
.update_customer_by_customer_id_merchant_id(
customer_id.to_owned(),
merchant_id.to_owned(),
+ customer,
customer_update,
&key_store,
+ storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
let resp = CustomerDefaultPaymentMethodResponse {
default_payment_method_id: updated_customer_details.default_payment_method_id,
- customer_id: customer.customer_id,
+ customer_id,
payment_method_type: payment_method.payment_method_type,
payment_method: payment_method.payment_method,
};
@@ -3556,6 +3572,7 @@ pub async fn delete_payment_method(
&key.customer_id,
&merchant_account.merchant_id,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
@@ -3599,8 +3616,10 @@ pub async fn delete_payment_method(
db.update_customer_by_customer_id_merchant_id(
key.customer_id,
key.merchant_id,
+ customer,
customer_update,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e74a8c1d1e..b9eed02f74 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -150,6 +150,7 @@ where
&mut payment_data,
customer_details,
&key_store,
+ merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
@@ -3490,6 +3491,7 @@ pub async fn payment_external_authentication(
customer_id,
&merchant_account.merchant_id,
&key_store,
+ storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 647854cca6..bde7e48983 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1284,6 +1284,7 @@ pub async fn get_customer_from_details<F: Clone>(
merchant_id: &str,
payment_data: &mut PaymentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
match customer_id {
None => Ok(None),
@@ -1293,6 +1294,7 @@ pub async fn get_customer_from_details<F: Clone>(
&c_id,
merchant_id,
merchant_key_store,
+ storage_scheme,
)
.await?;
payment_data.email = payment_data.email.clone().or_else(|| {
@@ -1431,6 +1433,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
req: Option<CustomerDetails>,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError> {
let request_customer_details = req
.get_required_value("customer")
@@ -1447,6 +1450,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
&customer_id,
merchant_id,
key_store,
+ storage_scheme,
)
.await?;
@@ -1498,8 +1502,10 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
db.update_customer_by_customer_id_merchant_id(
customer_id,
merchant_id.to_string(),
+ c,
customer_update,
key_store,
+ storage_scheme,
)
.await
} else {
@@ -1550,7 +1556,8 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while insert")?;
metrics::CUSTOMER_CREATED.add(&metrics::CONTEXT, 1, &[]);
- db.insert_customer(new_customer, key_store).await
+ db.insert_customer(new_customer, key_store, storage_scheme)
+ .await
}
})
}
@@ -1561,6 +1568,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
customer_id,
merchant_id,
key_store,
+ storage_scheme,
)
.await?
.map(Ok),
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index cad02fc721..261cbf0627 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -125,6 +125,7 @@ pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError>;
#[allow(clippy::too_many_arguments)]
@@ -240,6 +241,7 @@ where
payment_data: &mut PaymentData<F>,
_request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
@@ -255,6 +257,7 @@ where
&merchant_key_store.merchant_id,
payment_data,
merchant_key_store,
+ storage_scheme,
)
.await?,
))
@@ -322,6 +325,7 @@ where
payment_data: &mut PaymentData<F>,
_request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>,
@@ -337,6 +341,7 @@ where
&merchant_key_store.merchant_id,
payment_data,
merchant_key_store,
+ storage_scheme,
)
.await?,
))
@@ -395,6 +400,7 @@ where
payment_data: &mut PaymentData<F>,
_request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>,
@@ -410,6 +416,7 @@ where
&merchant_key_store.merchant_id,
payment_data,
merchant_key_store,
+ storage_scheme,
)
.await?,
))
@@ -469,6 +476,7 @@ where
_payment_data: &mut PaymentData<F>,
_request: Option<CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>,
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index e1a16b6f4a..03aa3685a4 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -326,6 +326,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
@@ -340,6 +341,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 8e66f43681..2151393006 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -652,6 +652,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
@@ -666,6 +667,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
@@ -1158,8 +1160,10 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
m_db.update_customer_by_customer_id_merchant_id(
m_customer_customer_id,
m_customer_merchant_id,
+ customer,
m_updated_customer,
&m_key_store,
+ storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index c6e95b176c..2e8b7eb9df 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -459,6 +459,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
@@ -473,6 +474,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 25b419e322..e15c413de2 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -300,6 +300,7 @@ where
payment_data: &mut PaymentData<F>,
request: Option<payments::CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
BoxedOperation<'a, F, api::PaymentsSessionRequest, Ctx>,
@@ -314,6 +315,7 @@ where
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 560d2014ba..cfa245ccc3 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -276,6 +276,7 @@ where
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>,
@@ -290,6 +291,7 @@ where
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 6739c2c3ba..39cd832871 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -71,6 +71,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
@@ -85,6 +86,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 934c0edfdd..fcf70212f3 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -464,6 +464,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
@@ -478,6 +479,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
request,
&key_store.merchant_id,
key_store,
+ storage_scheme,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index be2b127ff6..e73a829d04 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -294,6 +294,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve>
_payment_data: &mut payments::PaymentData<F>,
_request: Option<CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsIncrementalAuthorizationRequest, Ctx>,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index be4376d4f0..d333453eed 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -710,6 +710,7 @@ pub async fn payouts_list_core(
&payouts.customer_id,
merchant_id,
&key_store,
+ merchant_account.storage_scheme,
)
.await
{
@@ -1063,8 +1064,10 @@ pub async fn create_recipient(
db.update_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
+ customer,
updated_customer,
key_store,
+ merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -1838,6 +1841,7 @@ pub async fn make_payout_data(
&payouts.customer_id.to_owned(),
merchant_id,
key_store,
+ merchant_account.storage_scheme,
)
.await
.map_or(None, |c| c);
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index ef54cedcb8..089342b1a9 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -583,7 +583,12 @@ pub async fn get_or_create_customer_details(
let key = key_store.key.get_inner().peek();
match db
- .find_customer_optional_by_customer_id_merchant_id(&customer_id, merchant_id, key_store)
+ .find_customer_optional_by_customer_id_merchant_id(
+ &customer_id,
+ merchant_id,
+ key_store,
+ merchant_account.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
{
@@ -616,7 +621,7 @@ pub async fn get_or_create_customer_details(
};
Ok(Some(
- db.insert_customer(customer, key_store)
+ db.insert_customer(customer, key_store, merchant_account.storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?,
))
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 081a41e007..00fb7e4a08 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -1,29 +1,25 @@
use common_utils::ext_traits::AsyncExt;
-use error_stack::{report, ResultExt};
+use error_stack::ResultExt;
use futures::future::try_join_all;
-use masking::PeekInterface;
use router_env::{instrument, tracing};
-use super::{MockDb, Store};
+use super::MockDb;
use crate::{
- connection,
- core::{
- customers::REDACTED,
- errors::{self, CustomResult},
- },
+ core::errors::{self, CustomResult},
types::{
domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
- storage,
+ storage::{self as storage_types, enums::MerchantStorageScheme},
},
};
#[async_trait::async_trait]
pub trait CustomerInterface
where
- domain::Customer: Conversion<DstType = storage::Customer, NewDstType = storage::CustomerNew>,
+ domain::Customer:
+ Conversion<DstType = storage_types::Customer, NewDstType = storage_types::CustomerNew>,
{
async fn delete_customer_by_customer_id_merchant_id(
&self,
@@ -36,14 +32,17 @@ where
customer_id: &str,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError>;
async fn update_customer_by_customer_id_merchant_id(
&self,
customer_id: String,
merchant_id: String,
- customer: storage::CustomerUpdate,
+ customer: domain::Customer,
+ customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError>;
async fn find_customer_by_customer_id_merchant_id(
@@ -51,6 +50,7 @@ where
customer_id: &str,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError>;
async fn list_customers_by_merchant_id(
@@ -63,134 +63,423 @@ where
&self,
customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError>;
}
-#[async_trait::async_trait]
-impl CustomerInterface for Store {
- #[instrument(skip_all)]
- async fn find_customer_optional_by_customer_id_merchant_id(
- &self,
- customer_id: &str,
- merchant_id: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- let maybe_customer: Option<domain::Customer> =
- storage::Customer::find_optional_by_customer_id_merchant_id(
- &conn,
- customer_id,
- merchant_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?
- .async_map(|c| async {
- c.convert(key_store.key.get_inner())
+#[cfg(feature = "kv_store")]
+mod storage {
+ use common_utils::ext_traits::AsyncExt;
+ use diesel_models::kv;
+ use error_stack::{report, ResultExt};
+ use futures::future::try_join_all;
+ use masking::PeekInterface;
+ use router_env::{instrument, tracing};
+ use storage_impl::redis::kv_store::{kv_wrapper, KvOperation, PartitionKey};
+
+ use super::CustomerInterface;
+ use crate::{
+ connection,
+ core::{
+ customers::REDACTED,
+ errors::{self, CustomResult},
+ },
+ services::Store,
+ types::{
+ domain::{
+ self,
+ behaviour::{Conversion, ReverseConversion},
+ },
+ storage::{self as storage_types, enums::MerchantStorageScheme},
+ },
+ utils::db_utils,
+ };
+
+ #[async_trait::async_trait]
+ impl CustomerInterface for Store {
+ #[instrument(skip_all)]
+ // check customer not found in kv and fallback to db
+ async fn find_customer_optional_by_customer_id_merchant_id(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let database_call = || async {
+ storage_types::Customer::find_optional_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|err| report!(errors::StorageError::from(err)))
+ };
+
+ let maybe_customer = match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let key = PartitionKey::MerchantIdCustomerId {
+ merchant_id,
+ customer_id,
+ };
+ let field = format!("cust_{}", customer_id);
+ Box::pin(db_utils::try_redis_get_else_try_database_get(
+ // check for ValueNotFound
+ async {
+ kv_wrapper(
+ self,
+ KvOperation::<diesel_models::Customer>::HGet(&field),
+ key,
+ )
+ .await?
+ .try_into_hget()
+ .map(Some)
+ },
+ database_call,
+ ))
.await
- .change_context(errors::StorageError::DecryptionError)
- })
- .await
- .transpose()?;
- maybe_customer.map_or(Ok(None), |customer| {
- // in the future, once #![feature(is_some_and)] is stable, we can make this more concise:
- // `if customer.name.is_some_and(|ref name| name == REDACTED) ...`
- match customer.name {
+ }
+ }?;
+
+ let maybe_result = maybe_customer
+ .async_map(|c| async {
+ c.convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?;
+
+ maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name {
Some(ref name) if name.peek() == REDACTED => {
Err(errors::StorageError::CustomerRedacted)?
}
_ => Ok(Some(customer)),
- }
- })
- }
+ })
+ }
- #[instrument(skip_all)]
- async fn update_customer_by_customer_id_merchant_id(
- &self,
- customer_id: String,
- merchant_id: String,
- customer: storage::CustomerUpdate,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::Customer::update_by_customer_id_merchant_id(
- &conn,
- customer_id,
- merchant_id,
- customer.into(),
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|c| async {
- c.convert(key_store.key.get_inner())
+ #[instrument(skip_all)]
+ async fn update_customer_by_customer_id_merchant_id(
+ &self,
+ customer_id: String,
+ merchant_id: String,
+ customer: domain::Customer,
+ customer_update: storage_types::CustomerUpdate,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ let customer = Conversion::convert(customer)
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
+ let database_call = || async {
+ storage_types::Customer::update_by_customer_id_merchant_id(
+ &conn,
+ customer_id.clone(),
+ merchant_id.clone(),
+ customer_update.clone().into(),
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ };
+
+ let updated_object = match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let key = PartitionKey::MerchantIdCustomerId {
+ merchant_id: merchant_id.as_str(),
+ customer_id: customer_id.as_str(),
+ };
+ let field = format!("cust_{}", customer_id);
+ let updated_customer =
+ diesel_models::CustomerUpdateInternal::from(customer_update.clone())
+ .apply_changeset(customer.clone());
+
+ let redis_value = serde_json::to_string(&updated_customer)
+ .change_context(errors::StorageError::KVError)?;
+
+ let redis_entry = kv::TypedSql {
+ op: kv::DBOperation::Update {
+ updatable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
+ orig: customer,
+ update_data: customer_update.into(),
+ }),
+ },
+ };
+
+ kv_wrapper::<(), _, _>(
+ self,
+ KvOperation::Hset::<diesel_models::Customer>(
+ (&field, redis_value),
+ redis_entry,
+ ),
+ key,
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?
+ .try_into_hset()
+ .change_context(errors::StorageError::KVError)?;
+
+ Ok(updated_customer)
+ }
+ };
+
+ updated_object?
+ .convert(key_store.key.get_inner())
.await
.change_context(errors::StorageError::DecryptionError)
- })
- .await
- }
+ }
- #[instrument(skip_all)]
- async fn find_customer_by_customer_id_merchant_id(
- &self,
- customer_id: &str,
- merchant_id: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- let customer: domain::Customer =
- storage::Customer::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id)
+ #[instrument(skip_all)]
+ async fn find_customer_by_customer_id_merchant_id(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let database_call = || async {
+ storage_types::Customer::find_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
.await
.map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|c| async {
- c.convert(key_store.key.get_inner())
+ };
+
+ let customer = match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => database_call().await,
+ MerchantStorageScheme::RedisKv => {
+ let key = PartitionKey::MerchantIdCustomerId {
+ merchant_id,
+ customer_id,
+ };
+ let field = format!("cust_{}", customer_id);
+ Box::pin(db_utils::try_redis_get_else_try_database_get(
+ async {
+ kv_wrapper(
+ self,
+ KvOperation::<diesel_models::Customer>::HGet(&field),
+ key,
+ )
+ .await?
+ .try_into_hget()
+ },
+ database_call,
+ ))
+ .await
+ }
+ }?;
+
+ let result: domain::Customer = customer
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ //.await
+
+ match result.name {
+ Some(ref name) if name.peek() == REDACTED => {
+ Err(errors::StorageError::CustomerRedacted)?
+ }
+ _ => Ok(result),
+ }
+ }
+
+ #[instrument(skip_all)]
+ async fn list_customers_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ let encrypted_customers =
+ storage_types::Customer::list_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+
+ let customers = try_join_all(encrypted_customers.into_iter().map(
+ |encrypted_customer| async {
+ encrypted_customer
+ .convert(key_store.key.get_inner())
.await
.change_context(errors::StorageError::DecryptionError)
- })
- .await?;
- match customer.name {
- Some(ref name) if name.peek() == REDACTED => {
- Err(errors::StorageError::CustomerRedacted)?
- }
- _ => Ok(customer),
+ },
+ ))
+ .await?;
+
+ Ok(customers)
}
- }
- #[instrument(skip_all)]
- async fn list_customers_by_merchant_id(
- &self,
- merchant_id: &str,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
+ #[instrument(skip_all)]
+ async fn insert_customer(
+ &self,
+ customer_data: domain::Customer,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, errors::StorageError> {
+ let customer_id = customer_data.customer_id.clone();
+ let merchant_id = customer_data.merchant_id.clone();
+ let new_customer = customer_data
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
- let encrypted_customers = storage::Customer::list_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
+ let create_customer = match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ let conn = connection::pg_connection_write(self).await?;
+ new_customer
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+ MerchantStorageScheme::RedisKv => {
+ let key = PartitionKey::MerchantIdCustomerId {
+ merchant_id: merchant_id.as_str(),
+ customer_id: customer_id.as_str(),
+ };
+ let field = format!("cust_{}", customer_id.clone());
+
+ let redis_entry = kv::TypedSql {
+ op: kv::DBOperation::Insert {
+ insertable: kv::Insertable::Customer(new_customer.clone()),
+ },
+ };
+ let storage_customer = new_customer.into();
- let customers = try_join_all(encrypted_customers.into_iter().map(
- |encrypted_customer| async {
- encrypted_customer
- .convert(key_store.key.get_inner())
+ match kv_wrapper::<diesel_models::Customer, _, _>(
+ self,
+ KvOperation::HSetNx::<diesel_models::Customer>(
+ &field,
+ &storage_customer,
+ redis_entry,
+ ),
+ key,
+ )
.await
- .change_context(errors::StorageError::DecryptionError)
- },
- ))
- .await?;
+ .change_context(errors::StorageError::KVError)?
+ .try_into_hsetnx()
+ {
+ Ok(redis_interface::HsetnxReply::KeyNotSet) => {
+ Err(report!(errors::StorageError::DuplicateValue {
+ entity: "customer",
+ key: Some(customer_id),
+ }))
+ }
+ Ok(redis_interface::HsetnxReply::KeySet) => Ok(storage_customer),
+ Err(er) => Err(er).change_context(errors::StorageError::KVError),
+ }
+ }
+ }?;
- Ok(customers)
- }
+ create_customer
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
- #[instrument(skip_all)]
- async fn insert_customer(
- &self,
- customer_data: domain::Customer,
- key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- customer_data
- .construct_new()
+ #[instrument(skip_all)]
+ async fn delete_customer_by_customer_id_merchant_id(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ ) -> CustomResult<bool, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage_types::Customer::delete_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
.await
- .change_context(errors::StorageError::EncryptionError)?
- .insert(&conn)
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+ }
+}
+
+#[cfg(not(feature = "kv_store"))]
+mod storage {
+ use common_utils::ext_traits::AsyncExt;
+ use error_stack::{report, ResultExt};
+ use futures::future::try_join_all;
+ use masking::PeekInterface;
+ use router_env::{instrument, tracing};
+
+ use super::CustomerInterface;
+ use crate::{
+ connection,
+ core::{
+ customers::REDACTED,
+ errors::{self, CustomResult},
+ },
+ services::Store,
+ types::{
+ domain::{
+ self,
+ behaviour::{Conversion, ReverseConversion},
+ },
+ storage::{self as storage_types, enums::MerchantStorageScheme},
+ },
+ };
+
+ #[async_trait::async_trait]
+ impl CustomerInterface for Store {
+ #[instrument(skip_all)]
+ async fn find_customer_optional_by_customer_id_merchant_id(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let maybe_customer: Option<domain::Customer> =
+ storage_types::Customer::find_optional_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .async_map(|c| async {
+ c.convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?;
+ maybe_customer.map_or(Ok(None), |customer| {
+ // in the future, once #![feature(is_some_and)] is stable, we can make this more concise:
+ // `if customer.name.is_some_and(|ref name| name == REDACTED) ...`
+ match customer.name {
+ Some(ref name) if name.peek() == REDACTED => {
+ Err(errors::StorageError::CustomerRedacted)?
+ }
+ _ => Ok(Some(customer)),
+ }
+ })
+ }
+
+ #[instrument(skip_all)]
+ async fn update_customer_by_customer_id_merchant_id(
+ &self,
+ customer_id: String,
+ merchant_id: String,
+ _customer: domain::Customer,
+ customer_update: storage_types::CustomerUpdate,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage_types::Customer::update_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ customer_update.into(),
+ )
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|c| async {
@@ -199,18 +488,103 @@ impl CustomerInterface for Store {
.change_context(errors::StorageError::DecryptionError)
})
.await
- }
+ }
- #[instrument(skip_all)]
- async fn delete_customer_by_customer_id_merchant_id(
- &self,
- customer_id: &str,
- merchant_id: &str,
- ) -> CustomResult<bool, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::Customer::delete_by_customer_id_merchant_id(&conn, customer_id, merchant_id)
+ #[instrument(skip_all)]
+ async fn find_customer_by_customer_id_merchant_id(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let customer: domain::Customer =
+ storage_types::Customer::find_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|c| async {
+ c.convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?;
+ match customer.name {
+ Some(ref name) if name.peek() == REDACTED => {
+ Err(errors::StorageError::CustomerRedacted)?
+ }
+ _ => Ok(customer),
+ }
+ }
+
+ #[instrument(skip_all)]
+ async fn list_customers_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ let encrypted_customers =
+ storage_types::Customer::list_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+
+ let customers = try_join_all(encrypted_customers.into_iter().map(
+ |encrypted_customer| async {
+ encrypted_customer
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ },
+ ))
+ .await?;
+
+ Ok(customers)
+ }
+
+ #[instrument(skip_all)]
+ async fn insert_customer(
+ &self,
+ customer_data: domain::Customer,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ customer_data
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|c| async {
+ c.convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn delete_customer_by_customer_id_merchant_id(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ ) -> CustomResult<bool, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage_types::Customer::delete_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ )
.await
.map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
}
@@ -222,6 +596,7 @@ impl CustomerInterface for MockDb {
customer_id: &str,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
let customers = self.customers.lock().await;
let customer = customers
@@ -269,8 +644,10 @@ impl CustomerInterface for MockDb {
&self,
_customer_id: String,
_merchant_id: String,
- _customer: storage::CustomerUpdate,
+ _customer: domain::Customer,
+ _customer_update: storage_types::CustomerUpdate,
_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
@@ -281,6 +658,7 @@ impl CustomerInterface for MockDb {
_customer_id: &str,
_merchant_id: &str,
_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
@@ -291,6 +669,7 @@ impl CustomerInterface for MockDb {
&self,
customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
let mut customers = self.customers.lock().await;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0a56f4c27d..095c26e05a 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -324,9 +324,15 @@ impl CustomerInterface for KafkaStore {
customer_id: &str,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
- .find_customer_optional_by_customer_id_merchant_id(customer_id, merchant_id, key_store)
+ .find_customer_optional_by_customer_id_merchant_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
.await
}
@@ -334,15 +340,19 @@ impl CustomerInterface for KafkaStore {
&self,
customer_id: String,
merchant_id: String,
- customer: storage::CustomerUpdate,
+ customer: domain::Customer,
+ customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
customer,
+ customer_update,
key_store,
+ storage_scheme,
)
.await
}
@@ -362,9 +372,15 @@ impl CustomerInterface for KafkaStore {
customer_id: &str,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
- .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store)
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
.await
}
@@ -372,9 +388,10 @@ impl CustomerInterface for KafkaStore {
&self,
customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
- .insert_customer(customer_data, key_store)
+ .insert_customer(customer_data, key_store, storage_scheme)
.await
}
}
diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs
index af77991e80..4f82c29f5a 100644
--- a/crates/router_env/src/logger/setup.rs
+++ b/crates/router_env/src/logger/setup.rs
@@ -348,18 +348,14 @@ fn get_envfilter(
workspace_members
.drain()
- .zip(std::iter::repeat(filter_log_level.into_level()))
+ .zip(std::iter::repeat(filter_log_level.into_level().into()))
.fold(
EnvFilter::default().add_directive(default_log_level.into_level().into()),
- |env_filter, (target, level)| {
+ |env_filter, (_target, directive)| {
// Safety: This is a hardcoded basic filtering directive. If even the basic
// filter is wrong, it's better to panic.
#[allow(clippy::expect_used)]
- env_filter.add_directive(
- format!("{target}={level}")
- .parse()
- .expect("Invalid EnvFilter directive format"),
- )
+ env_filter.add_directive(directive)
},
)
})
diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs
new file mode 100644
index 0000000000..0d89e1c454
--- /dev/null
+++ b/crates/storage_impl/src/customers.rs
@@ -0,0 +1,5 @@
+use diesel_models::customers::Customer;
+
+use crate::redis::kv_store::KvStorePartition;
+
+impl KvStorePartition for Customer {}
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 20d018a6b7..91e308888b 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -8,6 +8,7 @@ use redis::{kv_store::RedisConnInterface, RedisStore};
mod address;
pub mod config;
pub mod connection;
+pub mod customers;
pub mod database;
pub mod errors;
mod lookup;
@@ -371,6 +372,18 @@ impl UniqueConstraints for diesel_models::PaymentMethod {
}
}
+impl UniqueConstraints for diesel_models::Customer {
+ fn unique_constraints(&self) -> Vec<String> {
+ vec![format!(
+ "customer_{}_{}",
+ self.customer_id, self.merchant_id
+ )]
+ }
+ fn table_name(&self) -> &str {
+ "Customer"
+ }
+}
+
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {}
#[cfg(not(feature = "payouts"))]