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(kv): add Redis KV support for captures table (#12630)

Hrithikesh392809c7a325
diff --git a/crates/diesel_models/src/kv/entity_type.rs b/crates/diesel_models/src/kv/entity_type.rs
index ea9c16864e..b2bdec2f37 100644
--- a/crates/diesel_models/src/kv/entity_type.rs
+++ b/crates/diesel_models/src/kv/entity_type.rs
@@ -54,4 +54,8 @@ entity_type! {
"reverse_lookup" => {
crate::reverse_lookup::ReverseLookupNew,
}
+ "capture" => {
+ crate::capture::CaptureNew,
+ crate::capture::CaptureUpdateInternal,
+ }
}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index b2832099da..fdce2ec142 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -72,8 +72,8 @@ use diesel_impl::{RequiredFromNullable, RequiredFromNullableWithDefault};
pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>;
pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
pub use self::{
- address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*,
- dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,
+ address::*, api_keys::*, callback_mapper::*, capture::*, cards_info::*, configs::*,
+ customers::*, dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,
hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*,
merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*,
payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*,
diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs
index 3f02948d2a..e7f33f4c3a 100644
--- a/crates/diesel_models/src/query/capture.rs
+++ b/crates/diesel_models/src/query/capture.rs
@@ -4,7 +4,7 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
capture::{Capture, CaptureNew, CaptureUpdate, CaptureUpdateInternal},
- errors,
+ errors, kv,
schema::captures::dsl,
PgPooledConn, StorageResult,
};
@@ -13,6 +13,13 @@ impl CaptureNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Capture> {
generics::generic_insert(conn, self).await
}
+
+ pub async fn generate_drainer_insert_query(
+ self,
+ conn: &mut PgPooledConn,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_insert_query(conn, self).await
+ }
}
impl Capture {
@@ -87,3 +94,18 @@ impl ConnectorTransactionIdTrait for Capture {
}
}
}
+
+impl CaptureUpdate {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ capture_id: String,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_by_id::<<Capture as HasTable>::Table, _, _>(
+ conn,
+ capture_id,
+ CaptureUpdateInternal::from(self),
+ )
+ .await
+ }
+}
diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs
index a2e4a90d66..d74da15e54 100644
--- a/crates/router/src/db/capture.rs
+++ b/crates/router/src/db/capture.rs
@@ -32,13 +32,19 @@ pub trait CaptureInterface {
#[cfg(feature = "kv_store")]
mod storage {
- use error_stack::report;
+ use error_stack::{report, ResultExt};
+ use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
+ use storage_impl::{
+ redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
+ utils::find_all_combined_kv_database,
+ KvSupportedEntity,
+ };
use super::CaptureInterface;
use crate::{
connection,
- core::errors::{self, CustomResult},
+ core::errors::{self, utils::RedisErrorExt, CustomResult},
services::Store,
types::storage::{capture::*, enums},
};
@@ -49,16 +55,77 @@ mod storage {
async fn insert_capture(
&self,
capture: CaptureNew,
- _storage_scheme: enums::MerchantStorageScheme,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Capture, errors::StorageError> {
- let db_call = || async {
- let conn = connection::pg_connection_write(self).await?;
- capture
- .insert(&conn)
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, Capture>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = connection::pg_connection_write(self).await?;
+ capture
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+ enums::MerchantStorageScheme::RedisKv => {
+ let created_capture = Capture {
+ capture_id: capture.capture_id.clone(),
+ payment_id: capture.payment_id.clone(),
+ merchant_id: capture.merchant_id.clone(),
+ status: capture.status,
+ amount: capture.amount,
+ currency: capture.currency,
+ connector: capture.connector.clone(),
+ error_message: capture.error_message.clone(),
+ error_code: capture.error_code.clone(),
+ error_reason: capture.error_reason.clone(),
+ tax_amount: capture.tax_amount,
+ created_at: capture.created_at,
+ modified_at: capture.created_at,
+ authorized_attempt_id: capture.authorized_attempt_id.clone(),
+ connector_capture_id: capture.connector_capture_id.clone(),
+ capture_sequence: capture.capture_sequence,
+ connector_response_reference_id: capture
+ .connector_response_reference_id
+ .clone(),
+ processor_capture_data: capture.processor_capture_data.clone(),
+ connector_capture_data: capture.connector_capture_data.clone(),
+ };
+
+ let key = created_capture.get_partition_key();
+ let key_str = key.to_string();
+ let field = created_capture.get_hash_field_key();
+
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = capture
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate capture insert query")?;
+
+ match Box::pin(kv_wrapper::<Capture, _, _>(
+ self,
+ KvOperation::<Capture>::HSetNx(&field, &created_capture, drainer_query),
+ key,
+ ))
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
- db_call().await
+ .map_err(|err| err.to_redis_failed_response(&key_str))?
+ .try_into_hsetnx()
+ {
+ Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
+ entity: "capture",
+ key: Some(created_capture.capture_id),
+ }
+ .into()),
+ Ok(HsetnxReply::KeySet) => Ok(created_capture),
+ Err(er) => Err(er).change_context(errors::StorageError::KVError),
+ }
+ }
+ }
}
#[instrument(skip_all)]
@@ -66,15 +133,50 @@ mod storage {
&self,
this: Capture,
capture: CaptureUpdate,
- _storage_scheme: enums::MerchantStorageScheme,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Capture, errors::StorageError> {
- let db_call = || async {
- let conn = connection::pg_connection_write(self).await?;
- this.update_with_capture_id(&conn, capture)
+ let key = this.get_partition_key();
+ let field = this.get_hash_field_key();
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, Capture>(
+ self,
+ storage_scheme,
+ Op::Update(key.clone(), &field, None),
+ ))
+ .await;
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = connection::pg_connection_write(self).await?;
+ this.update_with_capture_id(&conn, capture)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+ enums::MerchantStorageScheme::RedisKv => {
+ let key_str = key.to_string();
+ let updated_capture = capture.clone().apply_changeset(this.clone());
+
+ let redis_value = serde_json::to_string(&updated_capture)
+ .change_context(errors::StorageError::SerializationFailed)?;
+
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = capture
+ .generate_drainer_update_query(&mut query_gen_conn, this.capture_id.clone())
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate capture update query")?;
+
+ Box::pin(kv_wrapper::<(), _, _>(
+ self,
+ KvOperation::Hset::<Capture>((&field, redis_value), drainer_query),
+ key,
+ ))
.await
- .map_err(|error| report!(errors::StorageError::from(error)))
- };
- db_call().await
+ .map_err(|err| err.to_redis_failed_response(&key_str))?
+ .try_into_hset()
+ .change_context(errors::StorageError::KVError)?;
+
+ Ok(updated_capture)
+ }
+ }
}
#[instrument(skip_all)]
@@ -83,9 +185,9 @@ mod storage {
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
authorized_attempt_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Capture>, errors::StorageError> {
- let db_call = || async {
+ let database_call = || async {
let conn = connection::pg_connection_read(self).await?;
Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id(
merchant_id,
@@ -96,7 +198,43 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- db_call().await
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, Capture>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => database_call().await,
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = PartitionKey::MerchantIdPaymentId {
+ merchant_id,
+ payment_id,
+ };
+ let pattern = format!("pa_{authorized_attempt_id}_capture_*");
+
+ let redis_fut = async {
+ Box::pin(kv_wrapper(
+ self,
+ KvOperation::<Capture>::Scan(&pattern),
+ key,
+ ))
+ .await?
+ .try_into_scan()
+ };
+
+ let mut captures = Box::pin(find_all_combined_kv_database(
+ redis_fut,
+ database_call,
+ None,
+ ))
+ .await?;
+
+ captures.sort_by_key(|c| c.capture_sequence);
+
+ Ok(captures)
+ }
+ }
}
}
}
diff --git a/crates/storage_impl/src/capture.rs b/crates/storage_impl/src/capture.rs
new file mode 100644
index 0000000000..3fab876ae0
--- /dev/null
+++ b/crates/storage_impl/src/capture.rs
@@ -0,0 +1,5 @@
+use diesel_models::capture::Capture;
+
+use crate::redis::kv_store::KvStorePartition;
+
+impl KvStorePartition for Capture {}
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 7be52bcd73..919dbe608d 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -14,6 +14,7 @@ pub mod authentication;
pub mod behaviour;
pub mod business_profile;
pub mod callback_mapper;
+pub mod capture;
pub mod card_issuer;
pub mod cards_info;
pub mod config;
@@ -52,6 +53,7 @@ use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply};
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
+use crate::redis::kv_store;
pub use crate::{database::store::DatabaseStore, errors::StorageError};
#[derive(Debug, Clone)]
@@ -363,6 +365,27 @@ pub trait UniqueConstraints {
}
}
+/// This trait defines behaviour that must be followed by any table that has support for KV
+pub trait KvSupportedEntity: UniqueConstraints {
+ fn get_partition_key(&self) -> kv_store::PartitionKey<'_>;
+ fn get_hash_field_key(&self) -> String;
+}
+
+impl KvSupportedEntity for diesel_models::Capture {
+ fn get_partition_key(&self) -> kv_store::PartitionKey<'_> {
+ kv_store::PartitionKey::MerchantIdPaymentId {
+ merchant_id: &self.merchant_id,
+ payment_id: &self.payment_id,
+ }
+ }
+ fn get_hash_field_key(&self) -> String {
+ format!(
+ "pa_{}_capture_{}",
+ self.authorized_attempt_id, self.capture_id
+ )
+ }
+}
+
impl UniqueConstraints for diesel_models::Address {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("address_{}", self.address_id)]
@@ -510,6 +533,20 @@ impl UniqueConstraints for diesel_models::PaymentMethod {
}
}
+impl UniqueConstraints for diesel_models::Capture {
+ fn unique_constraints(&self) -> Vec<String> {
+ vec![format!(
+ "capture_{}_{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.authorized_attempt_id,
+ self.capture_id
+ )]
+ }
+ fn table_name(&self) -> &str {
+ "Capture"
+ }
+}
+
impl UniqueConstraints for diesel_models::Mandate {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(