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(drainer): store SQL queries in drainer stream instead of JSON-ified entities (#12449)

Sanchith Hegdea55673cc9abe
diff --git a/Cargo.lock b/Cargo.lock
index 926427151b..d41625842c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2951,6 +2951,7 @@ name = "diesel_models"
version = "0.1.0"
dependencies = [
"async-bb8-diesel",
+ "base64 0.22.1",
"common_enums",
"common_types",
"common_utils",
diff --git a/config/otel-collector.yaml b/config/otel-collector.yaml
index 9e64dbc4e2..96ad03ad14 100644
--- a/config/otel-collector.yaml
+++ b/config/otel-collector.yaml
@@ -25,7 +25,12 @@ service:
level: DEBUG
metrics:
level: detailed
- address: 0.0.0.0:8888
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: "0.0.0.0"
+ port: 8888
pipelines:
metrics:
diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs
index 29175777e8..d42191d8f0 100644
--- a/crates/common_utils/src/pii.rs
+++ b/crates/common_utils/src/pii.rs
@@ -163,6 +163,19 @@ where
}
}
+/// Masking strategy for binary data or raw bytes
+#[derive(Debug)]
+pub enum BinaryDataStrategy {}
+
+impl<T> Strategy<T> for BinaryDataStrategy
+where
+ T: AsRef<[u8]>,
+{
+ fn fmt(value: &T, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(fmt, "*** Binary data ({} bytes) ***", value.as_ref().len())
+ }
+}
+
/// Client secret
#[derive(Debug)]
pub enum ClientSecret {}
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index 04135b0390..807c247e24 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -16,7 +16,8 @@ tokenization_v2 = []
[dependencies]
async-bb8-diesel = "0.2.1"
-diesel = { version = "2.2.10", features = ["postgres", "serde_json", "time", "128-column-tables"] }
+base64 = "0.22.1"
+diesel = { version = "2.2.10", features = ["postgres", "serde_json", "time", "128-column-tables", "i-implement-a-third-party-backend-and-opt-into-breaking-changes"] }
error-stack = "0.4.1"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
diff --git a/crates/diesel_models/src/errors.rs b/crates/diesel_models/src/errors.rs
index 4a536aad07..f074ef36f2 100644
--- a/crates/diesel_models/src/errors.rs
+++ b/crates/diesel_models/src/errors.rs
@@ -8,16 +8,15 @@ pub enum DatabaseError {
UniqueViolation,
#[error("No fields were provided to be updated")]
NoFieldsToUpdate,
- #[error("An error occurred when generating typed SQL query")]
+ #[error("An error occurred when generating SQL query")]
QueryGenerationFailed,
- // InsertFailed,
#[error("An unknown error occurred")]
Others,
}
-impl From<diesel::result::Error> for DatabaseError {
- fn from(error: diesel::result::Error) -> Self {
- match error {
+impl common_utils::errors::ErrorSwitchFrom<diesel::result::Error> for DatabaseError {
+ fn switch_from(error: &diesel::result::Error) -> Self {
+ match *error {
diesel::result::Error::DatabaseError(
diesel::result::DatabaseErrorKind::UniqueViolation,
_,
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index d80cb969ca..af7da754f0 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -1,189 +1,155 @@
+mod bind_params;
+mod entity_type;
+mod pg_type_metadata;
+
+use async_bb8_diesel::AsyncConnection;
+use common_utils::pii;
+use diesel::{
+ associations::HasTable,
+ debug_query,
+ dsl::{Filter, Find},
+ pg::Pg,
+ query_builder::{
+ bind_collector::RawBytesBindCollector, AsChangeset, AsQuery, CollectedQuery,
+ InsertStatement, IntoUpdateTarget, MoveableBindCollector, QueryBuilder, QueryFragment,
+ UpdateStatement,
+ },
+ query_dsl::methods::{ExecuteDsl, FilterDsl, FindDsl},
+ query_source::Table,
+ Insertable,
+};
use error_stack::ResultExt;
-use serde::{Deserialize, Serialize};
+use hyperswitch_masking::Secret;
+use router_env::logger;
-#[cfg(feature = "v2")]
-use crate::payment_attempt::PaymentAttemptUpdateInternal;
-#[cfg(feature = "v1")]
-use crate::payment_intent::PaymentIntentUpdate;
-#[cfg(feature = "v2")]
-use crate::payment_intent::PaymentIntentUpdateInternal;
-use crate::{
- address::{Address, AddressNew, AddressUpdateInternal},
- customers::{Customer, CustomerNew, CustomerUpdateInternal},
- errors,
- payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
- payment_intent::PaymentIntentNew,
- payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
- payouts::{Payouts, PayoutsNew, PayoutsUpdate},
- refund::{Refund, RefundNew, RefundUpdate},
- reverse_lookup::{ReverseLookup, ReverseLookupNew},
- Mandate, MandateNew, MandateUpdateInternal, PaymentIntent, PaymentMethod, PaymentMethodNew,
- PaymentMethodUpdateInternal, PgPooledConn,
-};
+use crate::errors;
+
+type SecretBinaryData = Secret<Vec<u8>, pii::BinaryDataStrategy>;
+
+/// The SQL query and its bind parameters, in a (de)serialization-friendly representation
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct SerializableQuery {
+ /// The SQL query
+ sql: String,
+
+ /// The serialized bytes for each bind parameter
+ #[serde(with = "bind_params")]
+ binds: Vec<Option<SecretBinaryData>>,
+
+ /// The metadata associated with each bind parameter
+ #[serde(with = "pg_type_metadata")]
+ metadata: Vec<diesel::pg::PgTypeMetadata>,
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case", tag = "db_op", content = "data")]
-pub enum DBOperation {
- Insert { insertable: Box<Insertable> },
- Update { updatable: Box<Updateable> },
+ /// Whether this query is safe to store in the prepared statement cache
+ safe_to_cache_prepared: bool,
+
+ /// Entity type
+ entity_type: String,
+
+ /// The type of database operation
+ operation: DatabaseOperation,
}
-impl DBOperation {
- pub fn operation<'a>(&self) -> &'a str {
- match self {
- Self::Insert { .. } => "insert",
- Self::Update { .. } => "update",
- }
+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum DatabaseOperation {
+ Insert,
+ Update,
+}
+
+impl SerializableQuery {
+ pub fn entity_type(&self) -> String {
+ self.entity_type.clone()
+ }
+
+ pub fn operation(&self) -> DatabaseOperation {
+ self.operation
}
- pub fn table<'a>(&self) -> &'a str {
- match self {
- Self::Insert { insertable } => match **insertable {
- Insertable::PaymentIntent(_) => "payment_intent",
- Insertable::PaymentAttempt(_) => "payment_attempt",
- Insertable::Refund(_) => "refund",
- Insertable::Address(_) => "address",
- Insertable::Payouts(_) => "payouts",
- Insertable::PayoutAttempt(_) => "payout_attempt",
- Insertable::Customer(_) => "customer",
- Insertable::ReverseLookUp(_) => "reverse_lookup",
- Insertable::PaymentMethod(_) => "payment_method",
- Insertable::Mandate(_) => "mandate",
- },
- Self::Update { updatable } => match **updatable {
- Updateable::PaymentIntentUpdate(_) => "payment_intent",
- Updateable::PaymentAttemptUpdate(_) => "payment_attempt",
- Updateable::RefundUpdate(_) => "refund",
- Updateable::CustomerUpdate(_) => "customer",
- Updateable::AddressUpdate(_) => "address",
- Updateable::PayoutsUpdate(_) => "payouts",
- Updateable::PayoutAttemptUpdate(_) => "payout_attempt",
- Updateable::PaymentMethodUpdate(_) => "payment_method",
- Updateable::MandateUpdate(_) => " mandate",
- },
- }
+
+ async fn from_query<Q>(
+ conn: &mut crate::PgPooledConn,
+ query: Q,
+ entity_type: String,
+ operation: DatabaseOperation,
+ ) -> crate::StorageResult<Self>
+ where
+ Q: QueryFragment<Pg> + Send + 'static,
+ {
+ logger::debug!(%entity_type, %operation, query = %debug_query::<Pg, _>(&query).to_string());
+
+ let mut qb = diesel::pg::PgQueryBuilder::new();
+ query
+ .to_sql(&mut qb, &Pg)
+ .change_context(errors::DatabaseError::QueryGenerationFailed)
+ .attach_printable("Failed to construct SQL query")?;
+ let sql = qb.finish();
+
+ let safe_to_cache_prepared = query
+ .is_safe_to_cache_prepared(&Pg)
+ .change_context(errors::DatabaseError::QueryGenerationFailed)
+ .attach_printable(
+ "Failed to determine whether query is safe to store in prepared statement cache",
+ )?;
+
+ let bind_collector = conn
+ .run(move |c| {
+ let mut bc = RawBytesBindCollector::<Pg>::new();
+ query.collect_binds(&mut bc, c, &Pg)?;
+ Ok::<RawBytesBindCollector<Pg>, diesel::result::Error>(bc)
+ })
+ .await
+ .change_context(errors::DatabaseError::QueryGenerationFailed)
+ .attach_printable("Failed to construct bind parameters")?;
+
+ let serializable_query = Self {
+ sql,
+ binds: bind_collector
+ .binds
+ .into_iter()
+ .map(|option| option.map(Secret::new))
+ .collect(),
+ metadata: bind_collector.metadata.clone(),
+ safe_to_cache_prepared,
+ entity_type,
+ operation,
+ };
+
+ Ok(serializable_query)
}
-}
-#[derive(Debug)]
-pub enum DBResult {
- PaymentIntent(Box<PaymentIntent>),
- PaymentAttempt(Box<PaymentAttempt>),
- Refund(Box<Refund>),
- Address(Box<Address>),
- Customer(Box<Customer>),
- ReverseLookUp(Box<ReverseLookup>),
- Payouts(Box<Payouts>),
- PayoutAttempt(Box<PayoutAttempt>),
- PaymentMethod(Box<PaymentMethod>),
- Mandate(Box<Mandate>),
-}
+ fn to_collected_query(&self) -> CollectedQuery<RawBytesBindCollector<Pg>> {
+ use hyperswitch_masking::ExposeInterface;
+
+ let mut bind_collector = RawBytesBindCollector::<Pg>::new();
+ bind_collector.binds = self
+ .binds
+ .clone()
+ .into_iter()
+ .map(|option| option.map(ExposeInterface::expose))
+ .collect();
+ bind_collector.metadata = self.metadata.clone();
+
+ CollectedQuery::new(
+ self.sql.clone(),
+ self.safe_to_cache_prepared,
+ bind_collector.moveable(),
+ )
+ }
-#[derive(Debug, Serialize, Deserialize)]
-pub struct TypedSql {
- #[serde(flatten)]
- pub op: DBOperation,
-}
+ pub async fn execute(self, conn: &mut crate::PgPooledConn) -> crate::StorageResult<usize> {
+ use common_utils::errors::ReportSwitchExt;
-impl DBOperation {
- pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> {
- Ok(match self {
- Self::Insert { insertable } => match *insertable {
- Insertable::PaymentIntent(a) => {
- DBResult::PaymentIntent(Box::new(a.insert(conn).await?))
- }
- Insertable::PaymentAttempt(a) => {
- DBResult::PaymentAttempt(Box::new(a.insert(conn).await?))
- }
- 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?))
- }
- Insertable::Payouts(rev) => DBResult::Payouts(Box::new(rev.insert(conn).await?)),
- Insertable::PayoutAttempt(rev) => {
- DBResult::PayoutAttempt(Box::new(rev.insert(conn).await?))
- }
- Insertable::PaymentMethod(rev) => {
- DBResult::PaymentMethod(Box::new(rev.insert(conn).await?))
- }
- Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)),
- },
- Self::Update { updatable } => match *updatable {
- #[cfg(feature = "v1")]
- Updateable::PaymentIntentUpdate(a) => {
- DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
- }
- #[cfg(feature = "v2")]
- Updateable::PaymentIntentUpdate(a) => {
- DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
- }
- #[cfg(feature = "v1")]
- Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
- a.orig.update_with_attempt_id(conn, a.update_data).await?,
- )),
- #[cfg(feature = "v2")]
- Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
- a.orig.update_with_attempt_id(conn, a.update_data).await?,
- )),
- #[cfg(feature = "v1")]
- Updateable::RefundUpdate(a) => {
- DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?))
- }
- #[cfg(feature = "v2")]
- Updateable::RefundUpdate(a) => {
- DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?))
- }
- Updateable::AddressUpdate(a) => {
- DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?))
- }
- Updateable::PayoutsUpdate(a) => {
- DBResult::Payouts(Box::new(a.orig.update(conn, a.update_data).await?))
- }
- Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new(
- a.orig.update_with_attempt_id(conn, a.update_data).await?,
- )),
- #[cfg(feature = "v1")]
- Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
- v.orig
- .update_with_payment_method_id(conn, v.update_data)
- .await?,
- )),
- #[cfg(feature = "v2")]
- Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
- v.orig.update_with_id(conn, v.update_data).await?,
- )),
- Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new(
- Mandate::update_by_merchant_id_mandate_id(
- conn,
- &m.orig.merchant_id,
- &m.orig.mandate_id,
- m.update_data,
- )
- .await?,
- )),
- #[cfg(feature = "v1")]
- 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?,
- )),
- #[cfg(feature = "v2")]
- Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new(
- Customer::update_by_id(conn, cust.orig.id, cust.update_data).await?,
- )),
- },
- })
+ let query = self.to_collected_query();
+
+ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
+
+ conn.run(move |c| ExecuteDsl::execute(query, c))
+ .await
+ .attach_printable("Failed to execute drainer query")
+ .switch()
}
-}
-impl TypedSql {
pub fn to_field_value_pairs(
&self,
request_id: String,
@@ -193,7 +159,7 @@ impl TypedSql {
Ok(vec![
(
- "typed_sql",
+ "query",
serde_json::to_string(self)
.change_context(errors::DatabaseError::QueryGenerationFailed)?,
),
@@ -204,100 +170,64 @@ impl TypedSql {
}
}
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case", tag = "table", content = "data")]
-pub enum Insertable {
- PaymentIntent(Box<PaymentIntentNew>),
- PaymentAttempt(Box<PaymentAttemptNew>),
- Refund(RefundNew),
- Address(Box<AddressNew>),
- Customer(CustomerNew),
- ReverseLookUp(ReverseLookupNew),
- Payouts(PayoutsNew),
- PayoutAttempt(PayoutAttemptNew),
- PaymentMethod(Box<PaymentMethodNew>),
- Mandate(MandateNew),
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case", tag = "table", content = "data")]
-pub enum Updateable {
- PaymentIntentUpdate(Box<PaymentIntentUpdateMems>),
- PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>),
- RefundUpdate(Box<RefundUpdateMems>),
- CustomerUpdate(Box<CustomerUpdateMems>),
- AddressUpdate(Box<AddressUpdateMems>),
- PayoutsUpdate(PayoutsUpdateMems),
- PayoutAttemptUpdate(PayoutAttemptUpdateMems),
- PaymentMethodUpdate(Box<PaymentMethodUpdateMems>),
- MandateUpdate(MandateUpdateMems),
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct CustomerUpdateMems {
- pub orig: Customer,
- pub update_data: CustomerUpdateInternal,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct AddressUpdateMems {
- pub orig: Address,
- pub update_data: AddressUpdateInternal,
-}
-#[cfg(feature = "v1")]
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PaymentIntentUpdateMems {
- pub orig: PaymentIntent,
- pub update_data: PaymentIntentUpdate,
-}
-
-#[cfg(feature = "v2")]
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PaymentIntentUpdateMems {
- pub orig: PaymentIntent,
- pub update_data: PaymentIntentUpdateInternal,
-}
-
-#[cfg(feature = "v1")]
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PaymentAttemptUpdateMems {
- pub orig: PaymentAttempt,
- pub update_data: PaymentAttemptUpdate,
-}
-
-#[cfg(feature = "v2")]
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PaymentAttemptUpdateMems {
- pub orig: PaymentAttempt,
- pub update_data: PaymentAttemptUpdateInternal,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct RefundUpdateMems {
- pub orig: Refund,
- pub update_data: RefundUpdate,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PayoutsUpdateMems {
- pub orig: Payouts,
- pub update_data: PayoutsUpdate,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PayoutAttemptUpdateMems {
- pub orig: PayoutAttempt,
- pub update_data: PayoutAttemptUpdate,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PaymentMethodUpdateMems {
- pub orig: PaymentMethod,
- pub update_data: PaymentMethodUpdateInternal,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct MandateUpdateMems {
- pub orig: Mandate,
- pub update_data: MandateUpdateInternal,
+pub(crate) async fn generate_insert_query<T, N>(
+ conn: &mut crate::PgPooledConn,
+ new: N,
+) -> crate::StorageResult<SerializableQuery>
+where
+ T: HasTable<Table = T> + Table + Send + 'static,
+ N: Insertable<T> + entity_type::EntityType,
+ <N as Insertable<T>>::Values: QueryFragment<Pg> + Send + 'static,
+ InsertStatement<T, <N as Insertable<T>>::Values>: QueryFragment<Pg> + Send,
+{
+ let entity_type = N::ENTITY_TYPE.to_owned();
+ let query = diesel::insert_into(<T as HasTable>::table()).values(new);
+ SerializableQuery::from_query(conn, query, entity_type, DatabaseOperation::Insert)
+ .await
+ .attach_printable("Failed to generate insert query")
+}
+
+pub(crate) async fn generate_update_query_by_id<T, V, Pk>(
+ conn: &mut crate::PgPooledConn,
+ id: Pk,
+ values: V,
+) -> crate::StorageResult<SerializableQuery>
+where
+ T: FindDsl<Pk> + HasTable<Table = T> + Table + 'static,
+ V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + entity_type::EntityType,
+ Find<T, Pk>: IntoUpdateTarget + 'static,
+ UpdateStatement<
+ <Find<T, Pk> as HasTable>::Table,
+ <Find<T, Pk> as IntoUpdateTarget>::WhereClause,
+ <V as AsChangeset>::Changeset,
+ >: AsQuery + QueryFragment<Pg> + Send + 'static,
+ Pk: Clone,
+{
+ let entity_type = V::ENTITY_TYPE.to_owned();
+ let query = diesel::update(<T as HasTable>::table().find(id)).set(values);
+ SerializableQuery::from_query(conn, query, entity_type, DatabaseOperation::Update)
+ .await
+ .attach_printable("Failed to generate update query (with primary key)")
+}
+
+pub(crate) async fn generate_update_query_with_predicate<T, V, P>(
+ conn: &mut crate::PgPooledConn,
+ predicate: P,
+ values: V,
+) -> crate::StorageResult<SerializableQuery>
+where
+ T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
+ V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + entity_type::EntityType,
+ Filter<T, P>: IntoUpdateTarget + 'static,
+ UpdateStatement<
+ <Filter<T, P> as HasTable>::Table,
+ <Filter<T, P> as IntoUpdateTarget>::WhereClause,
+ <V as AsChangeset>::Changeset,
+ >: AsQuery + QueryFragment<Pg> + Send + 'static,
+{
+ let entity_type = V::ENTITY_TYPE.to_owned();
+ let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
+ SerializableQuery::from_query(conn, query, entity_type, DatabaseOperation::Update)
+ .await
+ .attach_printable("Failed to generate update query (with predicate)")
}
diff --git a/crates/diesel_models/src/kv/bind_params.rs b/crates/diesel_models/src/kv/bind_params.rs
new file mode 100644
index 0000000000..f958bf8f97
--- /dev/null
+++ b/crates/diesel_models/src/kv/bind_params.rs
@@ -0,0 +1,35 @@
+use base64::Engine;
+use common_utils::consts::BASE64_ENGINE;
+use hyperswitch_masking::{PeekInterface, Secret};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+use super::SecretBinaryData;
+
+pub fn serialize<S: Serializer>(
+ binds: &[Option<SecretBinaryData>],
+ s: S,
+) -> Result<S::Ok, S::Error> {
+ let encoded: Vec<Option<String>> = binds
+ .iter()
+ .map(|b| b.as_ref().map(|bytes| BASE64_ENGINE.encode(bytes.peek())))
+ .collect();
+ encoded.serialize(s)
+}
+
+pub fn deserialize<'de, D: Deserializer<'de>>(
+ d: D,
+) -> Result<Vec<Option<SecretBinaryData>>, D::Error> {
+ let encoded: Vec<Option<String>> = Vec::deserialize(d)?;
+ encoded
+ .into_iter()
+ .map(|b| {
+ b.map(|s| {
+ BASE64_ENGINE
+ .decode(&s)
+ .map(Secret::new)
+ .map_err(serde::de::Error::custom)
+ })
+ .transpose()
+ })
+ .collect()
+}
diff --git a/crates/diesel_models/src/kv/entity_type.rs b/crates/diesel_models/src/kv/entity_type.rs
new file mode 100644
index 0000000000..ea9c16864e
--- /dev/null
+++ b/crates/diesel_models/src/kv/entity_type.rs
@@ -0,0 +1,57 @@
+/// Associates a database type name with an entity type.
+pub(crate) trait EntityType {
+ const ENTITY_TYPE: &'static str;
+}
+
+macro_rules! entity_type {
+ ($($entity_name:literal => { $($type:path),* $(,)? })*) => {
+ $(
+ $(
+ impl EntityType for $type {
+ const ENTITY_TYPE: &'static str = $entity_name;
+ }
+ )*
+ )*
+ };
+}
+entity_type! {
+ "payment_intent" => {
+ crate::payment_intent::PaymentIntentNew,
+ crate::payment_intent::PaymentIntentUpdateInternal,
+ }
+ "payment_attempt" => {
+ crate::payment_attempt::PaymentAttemptNew,
+ crate::payment_attempt::PaymentAttemptUpdateInternal,
+ }
+ "customer" => {
+ crate::customers::CustomerNew,
+ crate::customers::CustomerUpdateInternal,
+ }
+ "refund" => {
+ crate::refund::RefundNew,
+ crate::refund::RefundUpdateInternal,
+ }
+ "mandate" => {
+ crate::mandate::MandateNew,
+ crate::mandate::MandateUpdateInternal,
+ }
+ "address" => {
+ crate::address::AddressNew,
+ crate::address::AddressUpdateInternal,
+ }
+ "payout_attempt" => {
+ crate::payout_attempt::PayoutAttemptNew,
+ crate::payout_attempt::PayoutAttemptUpdateInternal,
+ }
+ "payout" => {
+ crate::payouts::PayoutsNew,
+ crate::payouts::PayoutsUpdateInternal,
+ }
+ "payment_method" => {
+ crate::payment_method::PaymentMethodNew,
+ crate::payment_method::PaymentMethodUpdateInternal,
+ }
+ "reverse_lookup" => {
+ crate::reverse_lookup::ReverseLookupNew,
+ }
+}
diff --git a/crates/diesel_models/src/kv/pg_type_metadata.rs b/crates/diesel_models/src/kv/pg_type_metadata.rs
new file mode 100644
index 0000000000..dbcb721d8d
--- /dev/null
+++ b/crates/diesel_models/src/kv/pg_type_metadata.rs
@@ -0,0 +1,18 @@
+use diesel::pg::PgTypeMetadata;
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+pub fn serialize<S: Serializer>(metadata: &[PgTypeMetadata], s: S) -> Result<S::Ok, S::Error> {
+ let pairs: Vec<(u32, u32)> = metadata
+ .iter()
+ .map(|m| (m.oid().unwrap_or(0), m.array_oid().unwrap_or(0)))
+ .collect();
+ pairs.serialize(s)
+}
+
+pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<PgTypeMetadata>, D::Error> {
+ let pairs: Vec<(u32, u32)> = Vec::deserialize(d)?;
+ Ok(pairs
+ .into_iter()
+ .map(|(oid, array_oid)| PgTypeMetadata::from_result(Ok((oid, array_oid))))
+ .collect())
+}
diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rs
index 21304a6ab9..f7bb86cfbd 100644
--- a/crates/diesel_models/src/query/address.rs
+++ b/crates/diesel_models/src/query/address.rs
@@ -3,7 +3,7 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
address::{Address, AddressNew, AddressUpdateInternal},
- errors,
+ errors, kv,
schema::address::dsl,
PgPooledConn, StorageResult,
};
@@ -12,6 +12,13 @@ impl AddressNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Address> {
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 Address {
@@ -141,3 +148,18 @@ impl Address {
.await
}
}
+
+impl AddressUpdateInternal {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ address_id: String,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<Address as HasTable>::Table, _, _>(
+ conn,
+ dsl::address_id.eq(address_id),
+ self,
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rs
index e5a3d470dd..dffcfb4383 100644
--- a/crates/diesel_models/src/query/customers.rs
+++ b/crates/diesel_models/src/query/customers.rs
@@ -8,13 +8,20 @@ use crate::schema::customers::dsl;
use crate::schema_v2::customers::dsl;
use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
- errors, PgPooledConn, StorageResult,
+ errors, kv, PgPooledConn, StorageResult,
};
impl CustomerNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> {
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
+ }
}
pub struct CustomerListConstraints {
@@ -326,3 +333,29 @@ impl Customer {
.await
}
}
+
+impl CustomerUpdateInternal {
+ #[cfg(feature = "v1")]
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ customer_id: id_type::CustomerId,
+ merchant_id: id_type::MerchantId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_by_id::<<Customer as HasTable>::Table, _, _>(
+ conn,
+ (customer_id, merchant_id),
+ self,
+ )
+ .await
+ }
+
+ #[cfg(feature = "v2")]
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ id: id_type::GlobalCustomerId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_by_id::<<Customer as HasTable>::Table, _, _>(conn, id, self).await
+ }
+}
diff --git a/crates/diesel_models/src/query/mandate.rs b/crates/diesel_models/src/query/mandate.rs
index 4701473047..3dd4365f9e 100644
--- a/crates/diesel_models/src/query/mandate.rs
+++ b/crates/diesel_models/src/query/mandate.rs
@@ -2,12 +2,19 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, T
use error_stack::report;
use super::generics;
-use crate::{errors, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult};
+use crate::{errors, kv, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult};
impl MandateNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> {
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 Mandate {
@@ -104,3 +111,21 @@ impl Mandate {
})
}
}
+
+impl MandateUpdateInternal {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ merchant_id: common_utils::id_type::MerchantId,
+ mandate_id: String,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<Mandate as HasTable>::Table, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id)
+ .and(dsl::mandate_id.eq(mandate_id)),
+ self,
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index f2a18bb1f1..e2a2ed26ac 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -14,20 +14,28 @@ use super::generics;
use crate::schema::payment_attempt::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_attempt::dsl;
-#[cfg(feature = "v1")]
-use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent};
use crate::{
- enums::{self},
+ enums,
errors::DatabaseError,
+ kv,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal},
query::generics::db_metrics,
PgPooledConn, StorageResult,
};
+#[cfg(feature = "v1")]
+use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent};
impl PaymentAttemptNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> {
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 PaymentAttempt {
@@ -551,3 +559,41 @@ impl PaymentAttempt {
result
}
}
+
+#[cfg(feature = "v1")]
+impl PaymentAttemptUpdate {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ source_payment_attempt: &PaymentAttempt,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<PaymentAttempt as HasTable>::Table, _, _>(
+ conn,
+ dsl::attempt_id
+ .eq(source_payment_attempt.attempt_id.clone())
+ .and(
+ dsl::processor_merchant_id
+ .eq(source_payment_attempt.processor_merchant_id.clone()),
+ ),
+ PaymentAttemptUpdateInternal::from(self)
+ .populate_derived_fields(source_payment_attempt),
+ )
+ .await
+ }
+}
+
+#[cfg(feature = "v2")]
+impl PaymentAttemptUpdateInternal {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ id: common_utils::id_type::GlobalAttemptId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<PaymentAttempt as HasTable>::Table, _, _>(
+ conn,
+ dsl::id.eq(id),
+ self,
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rs
index f5312f4588..0cadf780a4 100644
--- a/crates/diesel_models/src/query/payment_intent.rs
+++ b/crates/diesel_models/src/query/payment_intent.rs
@@ -6,7 +6,7 @@ use crate::schema::payment_intent::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_intent::dsl;
use crate::{
- errors,
+ errors, kv,
payment_intent::{self, PaymentIntent, PaymentIntentNew},
PgPooledConn, StorageResult,
};
@@ -15,6 +15,13 @@ impl PaymentIntentNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> {
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 PaymentIntent {
@@ -149,3 +156,34 @@ impl PaymentIntent {
.await
}
}
+
+#[cfg(feature = "v1")]
+impl payment_intent::PaymentIntentUpdate {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ payment_id: common_utils::id_type::PaymentId,
+ processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<PaymentIntent as HasTable>::Table, _, _>(
+ conn,
+ dsl::payment_id
+ .eq(payment_id)
+ .and(dsl::processor_merchant_id.eq(processor_merchant_id)),
+ payment_intent::PaymentIntentUpdateInternal::from(self),
+ )
+ .await
+ }
+}
+
+#[cfg(feature = "v2")]
+impl payment_intent::PaymentIntentUpdateInternal {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ id: common_utils::id_type::GlobalPaymentId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_by_id::<<PaymentIntent as HasTable>::Table, _, _>(conn, id, self)
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 10f6fd0b66..200631d800 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -12,7 +12,7 @@ use crate::schema::payment_methods::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_methods::dsl::{self, id as pm_id};
use crate::{
- enums as storage_enums, errors,
+ enums as storage_enums, errors, kv,
payment_method::{self, PaymentMethod, PaymentMethodNew},
PgPooledConn, StorageResult,
};
@@ -21,6 +21,13 @@ impl PaymentMethodNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> {
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
+ }
}
#[cfg(feature = "v1")]
@@ -382,3 +389,33 @@ impl PaymentMethod {
.await
}
}
+
+impl payment_method::PaymentMethodUpdateInternal {
+ #[cfg(feature = "v1")]
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ payment_method_id: String,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<PaymentMethod as HasTable>::Table, _, _>(
+ conn,
+ dsl::payment_method_id.eq(payment_method_id),
+ self,
+ )
+ .await
+ }
+
+ #[cfg(feature = "v2")]
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ id: common_utils::id_type::GlobalPaymentMethodId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<PaymentMethod as HasTable>::Table, _, _>(
+ conn,
+ pm_id.eq(id),
+ self,
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index 45b8eb4fb2..28de010675 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -12,6 +12,7 @@ use super::generics;
use crate::{
enums,
errors::DatabaseError,
+ kv,
payout_attempt::{
PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,
},
@@ -23,6 +24,13 @@ impl PayoutAttemptNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> {
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 PayoutAttempt {
@@ -243,3 +251,21 @@ impl PayoutAttempt {
))
}
}
+
+impl PayoutAttemptUpdate {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ payout_attempt_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<PayoutAttempt as HasTable>::Table, _, _>(
+ conn,
+ dsl::payout_attempt_id
+ .eq(payout_attempt_id)
+ .and(dsl::merchant_id.eq(merchant_id)),
+ PayoutAttemptUpdateInternal::from(self),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rs
index dcb9d8e120..904a974316 100644
--- a/crates/diesel_models/src/query/payouts.rs
+++ b/crates/diesel_models/src/query/payouts.rs
@@ -7,7 +7,7 @@ use error_stack::{report, ResultExt};
use super::generics;
use crate::{
- enums, errors,
+ enums, errors, kv,
payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal},
query::generics::db_metrics,
schema::{payout_attempt, payouts::dsl},
@@ -18,6 +18,13 @@ impl PayoutsNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Payouts> {
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 Payouts {
pub async fn update(
@@ -137,3 +144,21 @@ impl Payouts {
.attach_printable("Error filtering count of payouts")
}
}
+
+impl PayoutsUpdate {
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ payout_id: common_utils::id_type::PayoutId,
+ merchant_id: common_utils::id_type::MerchantId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<Payouts as HasTable>::Table, _, _>(
+ conn,
+ dsl::payout_id
+ .eq(payout_id)
+ .and(dsl::merchant_id.eq(merchant_id)),
+ PayoutsUpdateInternal::from(self),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs
index 86c7701f43..f9e0ee8cd0 100644
--- a/crates/diesel_models/src/query/refund.rs
+++ b/crates/diesel_models/src/query/refund.rs
@@ -6,7 +6,7 @@ use crate::schema::refund::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::refund::dsl;
use crate::{
- errors,
+ errors, kv,
refund::{Refund, RefundNew, RefundUpdate, RefundUpdateInternal},
PgPooledConn, StorageResult,
};
@@ -15,6 +15,13 @@ impl RefundNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Refund> {
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
+ }
}
#[cfg(feature = "v1")]
@@ -285,3 +292,36 @@ impl Refund {
.await
}
}
+
+impl RefundUpdate {
+ #[cfg(feature = "v1")]
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ refund_id: String,
+ processor_merchant_id: common_utils::id_type::MerchantId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_with_predicate::<<Refund as HasTable>::Table, _, _>(
+ conn,
+ dsl::refund_id
+ .eq(refund_id)
+ .and(dsl::processor_merchant_id.eq(processor_merchant_id)),
+ RefundUpdateInternal::from(self),
+ )
+ .await
+ }
+
+ #[cfg(feature = "v2")]
+ pub async fn generate_drainer_update_query(
+ self,
+ conn: &mut PgPooledConn,
+ id: common_utils::id_type::GlobalRefundId,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_update_query_by_id::<<Refund as HasTable>::Table, _, _>(
+ conn,
+ id,
+ RefundUpdateInternal::from(self),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/reverse_lookup.rs b/crates/diesel_models/src/query/reverse_lookup.rs
index cfd4ab09a6..0c8417561b 100644
--- a/crates/diesel_models/src/query/reverse_lookup.rs
+++ b/crates/diesel_models/src/query/reverse_lookup.rs
@@ -2,6 +2,7 @@ use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
+ kv,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
schema::reverse_lookup::dsl,
PgPooledConn, StorageResult,
@@ -19,6 +20,13 @@ impl ReverseLookupNew {
generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?;
Ok(())
}
+
+ pub async fn generate_drainer_insert_query(
+ self,
+ conn: &mut PgPooledConn,
+ ) -> StorageResult<kv::SerializableQuery> {
+ kv::generate_insert_query(conn, self).await
+ }
}
impl ReverseLookup {
pub async fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self> {
diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml
index 1d949216c7..643ae43734 100644
--- a/crates/drainer/Cargo.toml
+++ b/crates/drainer/Cargo.toml
@@ -11,8 +11,8 @@ license.workspace = true
default = ["redis-rs"]
release = ["vergen", "external_services/aws_kms"]
vergen = ["router_env/vergen"]
-v1 = ["diesel_models/v1", "hyperswitch_interfaces/v1", "common_utils/v1"]
-v2 = ["diesel_models/v2", "hyperswitch_interfaces/v2", "common_utils/v2"]
+v1 = ["diesel_models/v1", "external_services/v1", "hyperswitch_interfaces/v1", "common_utils/v1"]
+v2 = ["diesel_models/v2", "external_services/v2", "hyperswitch_interfaces/v2", "common_utils/v2"]
fred = ["redis_interface/fred"]
redis-rs = ["redis_interface/redis-rs"]
diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs
index deced77b8d..db7889cbb5 100644
--- a/crates/drainer/src/handler.rs
+++ b/crates/drainer/src/handler.rs
@@ -248,22 +248,23 @@ async fn drainer(
for (entry_id, entry) in entries.clone() {
let data = match StreamData::from_hashmap(entry) {
Ok(data) => data,
- Err(err) => {
- logger::error!(operation = "deserialization", err=?err);
+ Err(error) => {
+ logger::error!(operation = "deserialization", ?error);
metrics::STREAM_PARSE_FAIL.add(
1,
router_env::metric_attributes!(("operation", "deserialization")),
);
- // break from the loop in case of a deser error
+ // break from the loop in case of a deserialization error
break;
}
};
tracing::Span::current().record("request_id", data.request_id);
tracing::Span::current().record("global_id", data.global_id);
+ logger::debug!("Processing stream entry");
- match data.typed_sql.execute_query(&store, data.pushed_at).await {
+ match data.query.execute_query(&store, data.pushed_at).await {
Ok(_) => {
last_processed_id = entry_id;
}
@@ -294,11 +295,11 @@ async fn drainer(
read_entries = %read_count,
trimmed_entries = %entries_trimmed,
?entries,
- "Assertion Failed no. of entries read from the stream doesn't match no. of entries trimmed"
+ "Assertion failed: no. of entries read from the stream doesn't match no. of entries trimmed"
);
}
} else {
- logger::error!(read_entries = %read_count,?entries,"No streams were processed in this session");
+ logger::error!(read_entries = %read_count, ?entries, "No streams were processed in this session");
}
Ok(())
diff --git a/crates/drainer/src/query.rs b/crates/drainer/src/query.rs
index ec6b271aa9..76f8a5c369 100644
--- a/crates/drainer/src/query.rs
+++ b/crates/drainer/src/query.rs
@@ -15,34 +15,37 @@ pub trait ExecuteQuery {
}
#[async_trait::async_trait]
-impl ExecuteQuery for kv::DBOperation {
+impl ExecuteQuery for kv::SerializableQuery {
async fn execute_query(
self,
store: &Arc<Store>,
pushed_at: i64,
) -> CustomResult<(), DatabaseError> {
- let conn = pg_connection(&store.master_pool).await;
- let operation = self.operation();
- let table = self.table();
+ let mut conn = pg_connection(&store.master_pool).await;
+ let operation = self.operation().to_string();
+ let entity_type = self.entity_type();
- let tags = router_env::metric_attributes!(("operation", operation), ("table", table));
+ let metric_attributes = router_env::metric_attributes!(
+ ("operation", operation.clone()),
+ ("entity_type", entity_type.clone())
+ );
let (result, execution_time) =
- Box::pin(common_utils::date_time::time_it(|| self.execute(&conn))).await;
+ common_utils::date_time::time_it(|| self.execute(&mut conn)).await;
- push_drainer_delay(pushed_at, operation, table, tags);
- metrics::QUERY_EXECUTION_TIME.record(execution_time, tags);
+ push_drainer_delay(pushed_at, &operation, &entity_type, metric_attributes);
+ metrics::QUERY_EXECUTION_TIME.record(execution_time, metric_attributes);
match result {
- Ok(result) => {
- logger::info!(operation = operation, table = table, ?result);
- metrics::SUCCESSFUL_QUERY_EXECUTION.add(1, tags);
+ Ok(rows_affected) => {
+ logger::info!(operation, entity_type, ?rows_affected);
+ metrics::SUCCESSFUL_QUERY_EXECUTION.add(1, metric_attributes);
Ok(())
}
- Err(err) => {
- logger::error!(operation = operation, table = table, ?err);
- metrics::ERRORS_WHILE_QUERY_EXECUTION.add(1, tags);
- Err(err)
+ Err(error) => {
+ logger::error!(operation, entity_type, ?error);
+ metrics::ERRORS_WHILE_QUERY_EXECUTION.add(1, metric_attributes);
+ Err(error)
}
}
}
@@ -52,16 +55,16 @@ impl ExecuteQuery for kv::DBOperation {
fn push_drainer_delay(
pushed_at: i64,
operation: &str,
- table: &str,
- tags: &[router_env::opentelemetry::KeyValue],
+ entity_type: &str,
+ metric_attributes: &[router_env::opentelemetry::KeyValue],
) {
let drained_at = common_utils::date_time::now_unix_timestamp();
let delay = drained_at - pushed_at;
- logger::debug!(operation, table, delay = format!("{delay} secs"));
+ logger::debug!(operation, entity_type, delay = format!("{delay} secs"));
match u64::try_from(delay) {
- Ok(delay) => metrics::DRAINER_DELAY_SECONDS.record(delay, tags),
+ Ok(delay) => metrics::DRAINER_DELAY_SECONDS.record(delay, metric_attributes),
Err(error) => logger::error!(
pushed_at,
drained_at,
diff --git a/crates/drainer/src/types.rs b/crates/drainer/src/types.rs
index 5c9fedf259..f39fecee97 100644
--- a/crates/drainer/src/types.rs
+++ b/crates/drainer/src/types.rs
@@ -6,15 +6,22 @@ use serde::{de::value::MapDeserializer, Deserialize, Serialize};
use crate::{
kv,
- utils::{deserialize_db_op, deserialize_i64},
+ utils::{deserialize_i64, deserialize_query},
};
#[derive(Deserialize, Serialize)]
pub struct StreamData {
+ /// Application request ID used for correlation
pub request_id: String,
+
+ /// Entity ID / Partitioning key
pub global_id: String,
- #[serde(deserialize_with = "deserialize_db_op")]
- pub typed_sql: kv::DBOperation,
+
+ /// Database SQL query
+ #[serde(deserialize_with = "deserialize_query")]
+ pub query: kv::SerializableQuery,
+
+ /// Time at which entry was pushed to stream
#[serde(deserialize_with = "deserialize_i64")]
pub pushed_at: i64,
}
diff --git a/crates/drainer/src/utils.rs b/crates/drainer/src/utils.rs
index 72f12c6049..b033375f21 100644
--- a/crates/drainer/src/utils.rs
+++ b/crates/drainer/src/utils.rs
@@ -39,7 +39,7 @@ where
}
}
-pub(crate) fn deserialize_db_op<'de, D>(deserializer: D) -> Result<kv::DBOperation, D::Error>
+pub(crate) fn deserialize_query<'de, D>(deserializer: D) -> Result<kv::SerializableQuery, D::Error>
where
D: serde::Deserializer<'de>,
{
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index ef4884fc52..6a57af6448 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -1,6 +1,6 @@
use std::str::FromStr;
-#[cfg(all(feature = "v1", feature = "olap"))]
+#[cfg(feature = "v1")]
use api_models::enums::Connector;
#[cfg(feature = "v1")]
use api_models::payments::Amount;
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 705486e602..7fc80f0df6 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -315,7 +315,7 @@ mod storage {
self,
behaviour::{Conversion, ReverseConversion},
},
- storage::{self as storage_types, kv},
+ storage::{self as storage_types},
},
utils::db_utils,
};
@@ -477,27 +477,29 @@ mod storage {
.await
}
MerchantStorageScheme::RedisKv => {
- let updated_address = AddressUpdateInternal::from(address_update.clone())
+ let address_update_internal =
+ AddressUpdateInternal::from(address_update.clone());
+ let updated_address = address_update_internal
+ .clone()
.create_address(address.clone());
let redis_value = serde_json::to_string(&updated_address)
.change_context(errors::StorageError::KVError)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::AddressUpdate(Box::new(
- kv::AddressUpdateMems {
- orig: address,
- update_data: address_update.into(),
- },
- ))),
- },
- };
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = address_update_internal
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ address.address_id.clone(),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate address update query")?;
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<storage_types::Address>(
(&field, redis_value),
- redis_entry,
+ drainer_query,
),
key,
))
@@ -588,18 +590,19 @@ mod storage {
origin_zip: address_new.origin_zip.clone(),
};
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::Address(Box::new(address_new))),
- },
- };
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = address_new
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate address insert query")?;
match Box::pin(kv_wrapper::<diesel_models::Address, _, _>(
self,
KvOperation::HSetNx::<diesel_models::Address>(
&field,
&created_address,
- redis_entry,
+ drainer_query,
),
key,
))
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index 9915b781f8..eb7a6b72b7 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -60,7 +60,6 @@ pub trait MandateInterface {
#[cfg(feature = "kv_store")]
mod storage {
use common_utils::{fallback_reverse_lookup_not_found, id_type};
- use diesel_models::kv;
use error_stack::{report, ResultExt};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
@@ -272,22 +271,22 @@ mod storage {
let redis_value = serde_json::to_string(&updated_mandate)
.change_context(errors::StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::MandateUpdate(
- kv::MandateUpdateMems {
- orig: mandate,
- update_data: m_update,
- },
- )),
- },
- };
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = m_update
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ merchant_id.clone(),
+ mandate_id.to_owned(),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate mandate update query")?;
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<diesel_models::Mandate>::Hset(
(&field, redis_value),
- redis_entry,
+ drainer_query,
),
key,
))
@@ -346,12 +345,6 @@ mod storage {
let storage_mandate = storage_types::Mandate::from(&mandate);
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::Mandate(mandate)),
- },
- };
-
if let Some(connector_val) = connector_mandate_id {
let lookup_id = format!(
"mid_{}_conn_mandate_{}",
@@ -371,12 +364,19 @@ mod storage {
.await?;
}
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = mandate
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate mandate insert query")?;
+
match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>(
self,
KvOperation::<diesel_models::Mandate>::HSetNx(
&field,
&storage_mandate,
- redis_entry,
+ drainer_query,
),
key,
))
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index e17cafe75d..5532678d7f 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -507,7 +507,7 @@ mod storage {
core::errors::{self, utils::RedisErrorExt, CustomResult},
db::reverse_lookup::ReverseLookupInterface,
services::Store,
- types::storage::{self as storage_types, enums, kv},
+ types::storage::{self as storage_types, enums},
utils::db_utils,
};
#[async_trait::async_trait]
@@ -669,12 +669,6 @@ mod storage {
&created_refund.attempt_id, &created_refund.refund_id
);
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::Refund(new)),
- },
- };
-
let mut reverse_lookups = vec![
storage_types::ReverseLookupNew {
sk_id: field.clone(),
@@ -722,12 +716,19 @@ mod storage {
futures::future::try_join_all(rev_look).await?;
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = new
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate refund insert query")?;
+
match Box::pin(kv_wrapper::<diesel_refund::Refund, _, _>(
self,
KvOperation::<diesel_refund::Refund>::HSetNx(
&field,
&created_refund,
- redis_entry,
+ drainer_query,
),
key,
))
@@ -890,22 +891,24 @@ mod storage {
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::RefundUpdate(Box::new(
- kv::RefundUpdateMems {
- orig: this,
- update_data: refund,
- },
- ))),
- },
- };
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = refund
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ this.refund_id.clone(),
+ this.processor_merchant_id
+ .clone()
+ .unwrap_or_else(|| merchant_id.clone()),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate refund update query")?;
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<diesel_refund::Refund>(
(&field, redis_value),
- redis_entry,
+ drainer_query,
),
key,
))
diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs
index 7704b4f71c..e6e8f7ee37 100644
--- a/crates/router/src/db/reverse_lookup.rs
+++ b/crates/router/src/db/reverse_lookup.rs
@@ -79,7 +79,7 @@ mod storage {
core::errors::utils::RedisErrorExt,
errors::{self, CustomResult},
types::storage::{
- enums, kv,
+ enums,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
},
utils::db_utils,
@@ -114,15 +114,16 @@ mod storage {
source: new.source.clone(),
updated_by: storage_scheme.to_string(),
};
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
- },
- };
+ let mut query_gen_conn = connection::pg_connection_write(self).await?;
+ let drainer_query = new
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate reverse lookup insert query")?;
match Box::pin(kv_wrapper::<ReverseLookup, _, _>(
self,
- KvOperation::SetNx(&created_rev_lookup, redis_entry),
+ KvOperation::SetNx(&created_rev_lookup, drainer_query),
PartitionKey::CombinationKey {
combination: &format!(
"reverse_lookup_{}",
diff --git a/crates/router/src/types/storage/kv.rs b/crates/router/src/types/storage/kv.rs
index 6bb6c38e7b..49f4455171 100644
--- a/crates/router/src/types/storage/kv.rs
+++ b/crates/router/src/types/storage/kv.rs
@@ -1,4 +1 @@
-pub use diesel_models::kv::{
- AddressUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems, PaymentIntentUpdateMems,
- RefundUpdateMems, TypedSql, Updateable,
-};
+pub use diesel_models::kv::SerializableQuery;
diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs
index 05ff222f8d..545e5a76b9 100644
--- a/crates/storage_impl/src/customers.rs
+++ b/crates/storage_impl/src/customers.rs
@@ -1,5 +1,5 @@
use common_utils::{id_type, pii};
-use diesel_models::{customers, kv};
+use diesel_models::customers;
use error_stack::ResultExt;
use futures::future::try_join_all;
use hyperswitch_domain_models::{
@@ -166,13 +166,28 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
let customer = Conversion::convert(customer)
.await
.change_context(StorageError::EncryptionError)?;
- let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone())
+ let customer_update_internal =
+ diesel_models::CustomerUpdateInternal::from(customer_update.clone());
+ let updated_customer = customer_update_internal
+ .clone()
.apply_changeset(customer.clone());
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
customer_id: &customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
+
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = customer_update_internal
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ customer_id.clone(),
+ merchant_id.clone(),
+ )
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate customer update query")?;
+
self.update_resource(
key_store,
storage_scheme,
@@ -184,10 +199,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
),
updated_customer,
kv_router_store::UpdateResourceParams {
- updateable: kv::Updateable::CustomerUpdate(Box::new(kv::CustomerUpdateMems {
- orig: customer.clone(),
- update_data: customer_update.clone().into(),
- })),
+ drainer_query,
operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
},
)
@@ -323,13 +335,21 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
reverse_lookups.push(reverse_lookup_merchant_scoped_id);
}
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = new_customer
+ .clone()
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate customer insert query")?;
+
self.insert_resource(
key_store,
decided_storage_scheme,
new_customer.clone().insert(&conn),
new_customer.clone().into(),
kv_router_store::InsertResourceParams {
- insertable: kv::Insertable::Customer(new_customer.clone()),
+ drainer_query,
reverse_lookups,
identifier,
key,
@@ -365,13 +385,22 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
.await;
new_customer.update_storage_scheme(storage_scheme);
let customer = new_customer.clone().into();
+
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = new_customer
+ .clone()
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate customer insert query")?;
+
self.insert_resource(
key_store,
storage_scheme,
new_customer.clone().insert(&conn),
customer,
kv_router_store::InsertResourceParams {
- insertable: kv::Insertable::Customer(new_customer.clone()),
+ drainer_query,
reverse_lookups: vec![],
identifier,
key,
@@ -472,23 +501,30 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
let customer = Conversion::convert(customer)
.await
.change_context(StorageError::EncryptionError)?;
+ let customer_update_internal =
+ diesel_models::CustomerUpdateInternal::from(customer_update.clone());
let database_call =
- customers::Customer::update_by_id(&conn, id.clone(), customer_update.clone().into());
+ customers::Customer::update_by_id(&conn, id.clone(), customer_update_internal.clone());
let key = PartitionKey::GlobalId {
id: id.get_string_repr(),
};
let field = format!("cust_{}", id.get_string_repr());
+
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = customer_update_internal
+ .clone()
+ .generate_drainer_update_query(&mut query_gen_conn, id.clone())
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate customer update query")?;
+
self.update_resource(
key_store,
storage_scheme,
database_call,
- diesel_models::CustomerUpdateInternal::from(customer_update.clone())
- .apply_changeset(customer.clone()),
+ customer_update_internal.apply_changeset(customer.clone()),
kv_router_store::UpdateResourceParams {
- updateable: kv::Updateable::CustomerUpdate(Box::new(kv::CustomerUpdateMems {
- orig: customer.clone(),
- update_data: customer_update.into(),
- })),
+ drainer_query,
operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
},
)
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 3aade73383..38484008ac 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -52,7 +52,10 @@ impl From<error_stack::Report<RedisError>> for StorageError {
impl From<diesel::result::Error> for StorageError {
fn from(err: diesel::result::Error) -> Self {
- Self::from(error_stack::report!(DatabaseError::from(err)))
+ use common_utils::errors::ErrorSwitchFrom;
+
+ let database_error = DatabaseError::switch_from(&err);
+ Self::from(error_stack::report!(err).change_context(database_error))
}
}
diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rs
index 9fa816d9a2..43c3e1b240 100644
--- a/crates/storage_impl/src/kv_router_store.rs
+++ b/crates/storage_impl/src/kv_router_store.rs
@@ -58,7 +58,7 @@ impl<T: DatabaseStore> KVRouterStore<T> {
}
pub struct InsertResourceParams<'a> {
- pub insertable: kv::Insertable,
+ pub drainer_query: kv::SerializableQuery,
pub reverse_lookups: Vec<String>,
pub key: PartitionKey<'a>,
// secondary key
@@ -68,7 +68,7 @@ pub struct InsertResourceParams<'a> {
}
pub struct UpdateResourceParams<'a> {
- pub updateable: kv::Updateable,
+ pub drainer_query: kv::SerializableQuery,
pub operation: Op<'a>,
}
@@ -191,7 +191,7 @@ impl<T: DatabaseStore> KVRouterStore<T> {
pub async fn push_to_drainer_stream<R>(
&self,
- redis_entry: kv::TypedSql,
+ serializable_query: kv::SerializableQuery,
partition_key: PartitionKey<'_>,
) -> error_stack::Result<(), RedisError>
where
@@ -202,20 +202,24 @@ impl<T: DatabaseStore> KVRouterStore<T> {
let shard_key = R::shard_key(partition_key, self.drainer_num_partitions);
let stream_name = self.get_drainer_stream_name(&shard_key);
+ let metric_attributes = router_env::metric_attributes!(
+ ("operation", serializable_query.operation().to_string()),
+ ("entity_type", serializable_query.entity_type())
+ );
self.router_store
.cache_store
.redis_conn
.stream_append_entry(
&stream_name.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
- redis_entry
+ serializable_query
.to_field_value_pairs(request_id, global_id)
.change_context(RedisError::JsonSerializationFailed)?,
)
.await
- .map(|_| metrics::KV_PUSHED_TO_DRAINER.add(1, &[]))
+ .map(|_| metrics::KV_PUSHED_TO_DRAINER.add(1, metric_attributes))
.inspect_err(|error| {
- metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(1, &[]);
+ metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(1, metric_attributes);
logger::error!(?error, "Failed to add entry in drainer stream");
})
.change_context(RedisError::StreamAppendFailed)
@@ -371,7 +375,7 @@ impl<T: DatabaseStore> KVRouterStore<T> {
create_resource_fut: R,
resource_new: M,
InsertResourceParams {
- insertable,
+ drainer_query,
reverse_lookups,
key,
identifier,
@@ -409,14 +413,9 @@ impl<T: DatabaseStore> KVRouterStore<T> {
futures::future::try_join_all(results).await?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(insertable),
- },
- };
match Box::pin(kv_wrapper::<M, _, _>(
self,
- KvOperation::<M>::HSetNx(&identifier, &resource_new, redis_entry),
+ KvOperation::<M>::HSetNx(&identifier, &resource_new, drainer_query),
key.clone(),
))
.await
@@ -450,7 +449,7 @@ impl<T: DatabaseStore> KVRouterStore<T> {
update_resource_fut: R,
updated_resource: M,
UpdateResourceParams {
- updateable,
+ drainer_query,
operation,
}: UpdateResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
@@ -479,14 +478,9 @@ impl<T: DatabaseStore> KVRouterStore<T> {
let redis_value = serde_json::to_string(&updated_resource)
.change_context(errors::StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(updateable),
- },
- };
Box::pin(kv_wrapper::<(), _, _>(
self,
- KvOperation::<M>::Hset((field, redis_value), redis_entry),
+ KvOperation::<M>::Hset((field, redis_value), drainer_query),
key,
))
.await
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
index 63bb5ab5c8..6c95d4bcdc 100644
--- a/crates/storage_impl/src/lookup.rs
+++ b/crates/storage_impl/src/lookup.rs
@@ -1,6 +1,6 @@
use common_utils::errors::CustomResult;
use diesel_models::{
- enums as storage_enums, kv,
+ enums as storage_enums,
reverse_lookup::{
ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew,
},
@@ -91,15 +91,17 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
source: new.source.clone(),
updated_by: storage_scheme.to_string(),
};
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
- },
- };
+
+ let mut query_gen_conn = utils::pg_connection_read(self).await?;
+ let drainer_query = new
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate reverse lookup insert query")?;
match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>(
self,
- KvOperation::SetNx(&created_rev_lookup, redis_entry),
+ KvOperation::SetNx(&created_rev_lookup, drainer_query),
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id),
},
diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs
index 5e00a7677a..8ca5c9d861 100644
--- a/crates/storage_impl/src/payment_method.rs
+++ b/crates/storage_impl/src/payment_method.rs
@@ -1,9 +1,3 @@
-pub use diesel_models::payment_method::PaymentMethod;
-
-use crate::redis::kv_store::KvStorePartition;
-
-impl KvStorePartition for PaymentMethod {}
-
#[cfg(feature = "v1")]
use std::collections::HashSet;
@@ -11,8 +5,7 @@ use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v2")]
use common_utils::ext_traits::OptionExt;
use common_utils::{errors::CustomResult, id_type};
-#[cfg(feature = "v1")]
-use diesel_models::kv;
+pub use diesel_models::payment_method::PaymentMethod;
use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
@@ -30,6 +23,7 @@ use super::MockDb;
use crate::{
diesel_error_to_data_error, errors,
kv_router_store::{FindResourceBy, KVRouterStore},
+ redis::kv_store::KvStorePartition,
utils::{pg_connection_read, pg_connection_write},
DatabaseStore, RouterStore,
};
@@ -39,6 +33,8 @@ use crate::{
redis::kv_store::{Op, PartitionKey},
};
+impl KvStorePartition for PaymentMethod {}
+
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
type Error = errors::StorageError;
@@ -185,13 +181,22 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
reverse_lookups.push(format!("payment_method_locker_{locker_id}"))
}
let payment_method = (&payment_method_new.clone()).into();
+
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = payment_method_new
+ .clone()
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payment method insert query")?;
+
self.insert_resource(
key_store,
storage_scheme,
payment_method_new.clone().insert(&conn),
payment_method,
InsertResourceParams {
- insertable: kv::Insertable::PaymentMethod(Box::new(payment_method_new.clone())),
+ drainer_query,
reverse_lookups,
key,
identifier,
@@ -225,6 +230,18 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
let p_update: PaymentMethodUpdateInternal =
payment_method_update.convert_to_payment_method_update(storage_scheme);
let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone());
+
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = p_update
+ .clone()
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ payment_method.payment_method_id.clone(),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payment method update query")?;
+
Box::pin(
self.update_resource(
key_store,
@@ -234,12 +251,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
.update_with_payment_method_id(&conn, p_update.clone()),
updated_payment_method,
UpdateResourceParams {
- updateable: kv::Updateable::PaymentMethodUpdate(Box::new(
- kv::PaymentMethodUpdateMems {
- orig: payment_method.clone(),
- update_data: p_update.clone(),
- },
- )),
+ drainer_query,
operation: Op::Update(
key.clone(),
&field,
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 1d605684c8..e0f0f20a47 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -6,7 +6,6 @@ use diesel_models::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
MandateDetails as DieselMandateDetails, MerchantStorageScheme,
},
- kv,
payment_attempt::PaymentAttempt as DieselPaymentAttempt,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
};
@@ -856,20 +855,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.sender_payment_instrument_id
.clone(),
};
-
+ let payment_attempt_new = payment_attempt
+ .clone()
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
let field = format!("pa_{}", created_attempt.attempt_id);
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new(
- payment_attempt
- .construct_new()
- .await
- .change_context(errors::StorageError::EncryptionError)?,
- ))),
- },
- };
-
//Reverse lookup for attempt_id
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
@@ -885,6 +877,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = payment_attempt_new
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payment attempt insert query")?;
+
match Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>(
self,
KvOperation::HSetNx(
@@ -894,7 +893,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.convert()
.await
.change_context(errors::StorageError::EncryptionError)?,
- redis_entry,
+ drainer_query,
),
key,
))
@@ -961,14 +960,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.await
.change_context(errors::StorageError::EncryptionError)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new(
- diesel_payment_attempt_new.clone(),
- ))),
- },
- };
-
let reverse_lookup_attempt_id = ReverseLookupNew {
lookup_id: label::get_global_id_label(&payment_attempt.id),
pk_id: key_str.clone(),
@@ -994,9 +985,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.await?;
}
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = diesel_payment_attempt_new
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payment attempt insert query")?;
+
match Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>(
self,
- KvOperation::HSetNx(&field, &diesel_payment_attempt_for_redis, redis_entry),
+ KvOperation::HSetNx(&field, &diesel_payment_attempt_for_redis, drainer_query),
key,
))
.await
@@ -1053,14 +1051,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let key_manager_state = self
.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?;
+ let source_payment_attempt_diesel = this
+ .clone()
+ .convert()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
+ let updated_payment_attempt_diesel = payment_attempt.to_storage_model();
let updated_attempt = PaymentAttempt::convert_back(
key_manager_state,
- payment_attempt.clone().to_storage_model().apply_changeset(
- this.clone()
- .convert()
- .await
- .change_context(errors::StorageError::EncryptionError)?,
- ),
+ updated_payment_attempt_diesel
+ .clone()
+ .apply_changeset(source_payment_attempt_diesel.clone()),
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
@@ -1068,24 +1069,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.change_context(errors::StorageError::EncryptionError)
.attach_printable("Error while constructing domain model")?;
// Check for database presence as well Maybe use a read replica here ?
- let redis_value = serde_json::to_string(&updated_attempt)
+ let redis_value = serde_json::to_string(&updated_payment_attempt_diesel)
.change_context(errors::StorageError::KVError)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new(
- kv::PaymentAttemptUpdateMems {
- orig: this
- .clone()
- .convert()
- .await
- .change_context(errors::StorageError::EncryptionError)?,
- update_data: payment_attempt.to_storage_model(),
- },
- ))),
- },
- };
-
match (
old_connector_transaction_id,
&updated_attempt.get_connector_payment_id(),
@@ -1145,9 +1131,19 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
(_, _) => {}
}
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = updated_payment_attempt_diesel
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ &source_payment_attempt_diesel,
+ )
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payment attempt update query")?;
+
Box::pin(kv_wrapper::<(), _, _>(
self,
- KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), redis_entry),
+ KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), drainer_query),
key,
))
.await
@@ -1191,18 +1187,20 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.clone()
.update_with_attempt_id(&conn, payment_attempt_internal.clone());
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = payment_attempt_internal
+ .generate_drainer_update_query(&mut query_gen_conn, payment_attempt.id.clone())
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payment attempt update query")?;
+
Box::pin(self.update_resource(
merchant_key_store,
storage_scheme,
updated_payment_attempt_with_id,
updated_payment_attempt,
UpdateResourceParams {
- updateable: kv::Updateable::PaymentAttemptUpdate(Box::new(
- kv::PaymentAttemptUpdateMems {
- orig: payment_attempt,
- update_data: payment_attempt_internal,
- },
- )),
+ drainer_query,
operation: Op::Update(key.clone(), &field, Some(updated_by.as_str())),
},
))
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 5e219d5771..ea5d8df4c0 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -26,7 +26,7 @@ use diesel_models::schema_v2::{
payment_intent::dsl as pi_dsl,
};
use diesel_models::{
- enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent,
+ enums::MerchantStorageScheme, payment_intent::PaymentIntent as DieselPaymentIntent,
};
use error_stack::ResultExt;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -99,26 +99,25 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await
.change_context(StorageError::EncryptionError)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::PaymentIntent(Box::new(
- new_payment_intent,
- ))),
- },
- };
-
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = new_payment_intent
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate payment intent insert query")?;
+
match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HSetNx(
&field,
&diesel_payment_intent,
- redis_entry,
+ drainer_query,
),
key,
))
@@ -164,14 +163,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await
.change_context(StorageError::EncryptionError)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::PaymentIntent(Box::new(
- new_payment_intent,
- ))),
- },
- };
-
let diesel_payment_intent = payment_intent
.clone()
.convert()
@@ -194,12 +185,19 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await?;
}
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = new_payment_intent
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate payment intent insert query")?;
+
match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HSetNx(
&field,
&diesel_payment_intent,
- redis_entry,
+ drainer_query,
),
key,
))
@@ -289,20 +287,20 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new(
- kv::PaymentIntentUpdateMems {
- orig: origin_diesel_intent,
- update_data: diesel_intent_update,
- },
- ))),
- },
- };
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = diesel_intent_update
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ origin_diesel_intent.payment_id.clone(),
+ origin_diesel_intent.processor_merchant_id.clone(),
+ )
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate payment intent update query")?;
Box::pin(kv_wrapper::<(), _, _>(
self,
- KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry),
+ KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), drainer_query),
key,
))
.await
@@ -368,20 +366,19 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new(
- kv::PaymentIntentUpdateMems {
- orig: origin_diesel_intent,
- update_data: diesel_intent_update,
- },
- ))),
- },
- };
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = diesel_intent_update
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ origin_diesel_intent.id.clone(),
+ )
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate payment intent update query")?;
Box::pin(kv_wrapper::<(), _, _>(
self,
- KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry),
+ KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), drainer_query),
key,
))
.await
@@ -1030,10 +1027,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payment records"),
- )
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payment records")
})?
.await
}
@@ -1094,11 +1089,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
)
.await
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payment records"),
- )
- .into()
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payment records")
})
}
@@ -1327,10 +1319,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
})
.await
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payment records"),
- )
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payment records")
})?
}
@@ -1640,11 +1630,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
)
.await
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payment records"),
- )
- .into()
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payment records")
})
}
@@ -1727,11 +1714,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
)
.await
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payment records"),
- )
- .into()
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payment records")
})
}
}
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 8ca38c7f08..d50c3e0758 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -4,7 +4,6 @@ use api_models::enums::PayoutConnectors;
use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found};
use diesel_models::{
enums::MerchantStorageScheme,
- kv,
payout_attempt::{
PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew,
PayoutAttemptUpdate as DieselPayoutAttemptUpdate,
@@ -100,15 +99,6 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
.clone(),
};
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::PayoutAttempt(
- new_payout_attempt.to_storage_model(),
- )),
- },
- };
-
- // Reverse lookup for payout_attempt_id
let field = format!("poa_{}", created_attempt.payout_attempt_id);
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
@@ -124,12 +114,20 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = new_payout_attempt
+ .to_storage_model()
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payout attempt insert query")?;
+
match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>(
self,
KvOperation::<DieselPayoutAttempt>::HSetNx(
&field,
&created_attempt.clone().to_storage_model(),
- redis_entry,
+ drainer_query,
),
key,
))
@@ -189,17 +187,6 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::PayoutAttemptUpdate(
- kv::PayoutAttemptUpdateMems {
- orig: origin_diesel_payout,
- update_data: diesel_payout_update,
- },
- )),
- },
- };
-
let updated_attempt = PayoutAttempt::from_storage_model(
payout_update
.to_storage_model()
@@ -236,9 +223,21 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
_ => {}
}
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = diesel_payout_update
+ .clone()
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ this.payout_attempt_id.clone(),
+ this.merchant_id.clone(),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)
+ .attach_printable("Failed to generate payout attempt update query")?;
+
Box::pin(kv_wrapper::<(), _, _>(
self,
- KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry),
+ KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), drainer_query),
key,
))
.await
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 2dcc5f25fc..c8188f15f1 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -14,7 +14,6 @@ use diesel_models::{
};
use diesel_models::{
enums::MerchantStorageScheme,
- kv,
payouts::{
Payouts as DieselPayouts, PayoutsNew as DieselPayoutsNew,
PayoutsUpdate as DieselPayoutsUpdate,
@@ -111,18 +110,20 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
created_by: new.created_by.clone(),
};
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())),
- },
- };
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = new
+ .to_storage_model()
+ .generate_drainer_insert_query(&mut query_gen_conn)
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate payouts insert query")?;
match Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HSetNx(
&field,
&created_payout.clone().to_storage_model(),
- redis_entry,
+ drainer_query,
),
key,
))
@@ -182,18 +183,21 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems {
- orig: origin_diesel_payout,
- update_data: diesel_payout_update,
- })),
- },
- };
+ let mut query_gen_conn = pg_connection_write(self).await?;
+ let drainer_query = diesel_payout_update
+ .clone()
+ .generate_drainer_update_query(
+ &mut query_gen_conn,
+ this.payout_id.clone(),
+ this.merchant_id.clone(),
+ )
+ .await
+ .change_context(StorageError::KVError)
+ .attach_printable("Failed to generate payouts update query")?;
Box::pin(kv_wrapper::<(), _, _>(
self,
- KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry),
+ KvOperation::<DieselPayouts>::Hset((&field, redis_value), drainer_query),
key,
))
.await
@@ -569,11 +573,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
.collect::<Vec<Payouts>>()
})
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payout records"),
- )
- .into()
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payout records")
})
}
@@ -737,11 +738,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
.collect()
})
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payout records"),
- )
- .into()
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payout records")
})
}
@@ -888,10 +886,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
)
.await
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payout records"),
- )
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payout records")
})?
.into_iter()
.map(|s| {
@@ -948,11 +944,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
)
.await
.map_err(|er| {
- StorageError::DatabaseError(
- error_stack::report!(diesel_models::errors::DatabaseError::from(er))
- .attach_printable("Error filtering payout records"),
- )
- .into()
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering payout records")
})
}
}
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index 6ee6f60af8..0c87e1ce14 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -8,7 +8,7 @@ use router_derive::TryGetEnumVariant;
use router_env::logger;
use serde::de;
-use crate::{kv_router_store::KVRouterStore, metrics, store::kv::TypedSql, UniqueConstraints};
+use crate::{kv_router_store::KVRouterStore, metrics, store::kv, UniqueConstraints};
pub trait KvStorePartition {
fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 {
@@ -20,7 +20,6 @@ pub trait KvStorePartition {
}
}
-#[allow(unused)]
#[derive(Clone)]
pub enum PartitionKey<'a> {
MerchantIdPaymentId {
@@ -130,9 +129,9 @@ pub trait RedisConnInterface {
/// An enum to represent what operation to do on
pub enum KvOperation<'a, S: serde::Serialize + Debug> {
- Hset((&'a str, String), TypedSql),
- SetNx(&'a S, TypedSql),
- HSetNx(&'a str, &'a S, TypedSql),
+ Hset((&'a str, String), kv::SerializableQuery),
+ SetNx(&'a S, kv::SerializableQuery),
+ HSetNx(&'a str, &'a S, kv::SerializableQuery),
HGet(&'a str),
Get,
Scan(&'a str),
@@ -186,7 +185,7 @@ where
let result = async {
match op {
- KvOperation::Hset(value, sql) => {
+ KvOperation::Hset(value, query) => {
logger::debug!(kv_operation= %operation, value = ?value);
redis_conn
@@ -194,7 +193,7 @@ where
.await?;
store
- .push_to_drainer_stream::<S>(sql, partition_key)
+ .push_to_drainer_stream::<S>(query, partition_key)
.await?;
Ok(KvResult::Hset(()))
@@ -221,7 +220,7 @@ where
Ok(KvResult::Scan(result))
}
- KvOperation::HSetNx(field, value, sql) => {
+ KvOperation::HSetNx(field, value, query) => {
logger::debug!(kv_operation= %operation, value = ?value);
value.check_for_constraints(&redis_conn).await?;
@@ -232,7 +231,7 @@ where
if matches!(result, redis_interface::HsetnxReply::KeySet) {
store
- .push_to_drainer_stream::<S>(sql, partition_key)
+ .push_to_drainer_stream::<S>(query, partition_key)
.await?;
Ok(KvResult::HSetNx(result))
} else {
@@ -240,7 +239,7 @@ where
}
}
- KvOperation::SetNx(value, sql) => {
+ KvOperation::SetNx(value, query) => {
logger::debug!(kv_operation= %operation, value = ?value);
let result = redis_conn
@@ -251,7 +250,7 @@ where
if matches!(result, redis_interface::SetnxReply::KeySet) {
store
- .push_to_drainer_stream::<S>(sql, partition_key)
+ .push_to_drainer_stream::<S>(query, partition_key)
.await?;
Ok(KvResult::SetNx(result))
} else {
@@ -339,7 +338,7 @@ where
};
let type_name = std::any::type_name::<D>();
- logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops);
+ logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme, entity = %type_name, operation = %ops);
updated_scheme
} else {
diff --git a/justfile b/justfile
index 4bc74e0201..b378f05640 100644
--- a/justfile
+++ b/justfile
@@ -88,7 +88,6 @@ build_v2 redis_interface_backend="redis-rs" *FLAGS:
cargo build --package router --bin router --no-default-features --features "${FEATURES}" {{ FLAGS }}
set +x
-
# redis_interface_backend: "redis-rs" (default) or "fred"
run_v2 redis_interface_backend="redis-rs":
#! /usr/bin/env bash
@@ -175,6 +174,14 @@ payment-link-wasm features='' version='v1' environment='development':
# Run pre-commit checks
precommit: fmt clippy
+# Run drainer with v1 features enabled
+drainer redis_interface_backend="redis-rs" *FLAGS:
+ DRAINER__SERVER__PORT=8084 cargo run --package drainer --no-default-features --features "{{ redis_interface_backend }},v1" {{ FLAGS }}
+
+# Run drainer with v2 features enabled
+drainer_v2 redis_interface_backend="redis-rs" *FLAGS:
+ DRAINER__SERVER__PORT=8084 cargo run --package drainer --no-default-features --features "{{ redis_interface_backend }},v2" {{ FLAGS }}
+
# Use the env variables if present, or fallback to default values
db_user := env_var_or_default('DB_USER', 'db_user')
@@ -194,16 +201,16 @@ resultant_dir := source_directory() / 'final-migrations'
[private]
prefix_and_copy_migrations dir_1 dir_2 prefix resultant_dir:
#! /usr/bin/env bash
- mkdir -p {{resultant_dir}}
- cp -r {{dir_1}}/* {{resultant_dir}}/ > /dev/null 2>&1
+ mkdir -p {{ resultant_dir }}
+ cp -r {{ dir_1 }}/* {{ resultant_dir }}/ > /dev/null 2>&1
- # Prefix v2 migrations with {{prefix}}
+ # Prefix v2 migrations with {{ prefix }}
sh -c '
- for dir in "{{dir_2}}"/*; do
+ for dir in "{{ dir_2 }}"/*; do
if [ -d "${dir}" ]; then
base_name=$(basename "${dir}")
- new_name="{{prefix}}${base_name}"
- cp -r "${dir}" "{{resultant_dir}}/${new_name}"
+ new_name="{{ prefix }}${base_name}"
+ cp -r "${dir}" "{{ resultant_dir }}/${new_name}"
fi
done
'