repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/hyperswitch_ai_interaction.rs
crates/diesel_models/src/hyperswitch_ai_interaction.rs
use common_utils::encryption::Encryption; use diesel::{self, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::schema::hyperswitch_ai_interaction; #[derive( Clone, Debug, Deserialize, Identifiable, Queryable, Selectable, Serialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = hyperswitch_ai_interaction, primary_key(id, created_at), check_for_backend(diesel::pg::Pg))] pub struct HyperswitchAiInteraction { pub id: String, pub session_id: Option<String>, pub user_id: Option<String>, pub merchant_id: Option<String>, pub profile_id: Option<String>, pub org_id: Option<String>, pub role_id: Option<String>, pub user_query: Option<Encryption>, pub response: Option<Encryption>, pub database_query: Option<String>, pub interaction_status: Option<String>, pub created_at: PrimitiveDateTime, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = hyperswitch_ai_interaction)] pub struct HyperswitchAiInteractionNew { pub id: String, pub session_id: Option<String>, pub user_id: Option<String>, pub merchant_id: Option<String>, pub profile_id: Option<String>, pub org_id: Option<String>, pub role_id: Option<String>, pub user_query: Option<Encryption>, pub response: Option<Encryption>, pub database_query: Option<String>, pub interaction_status: Option<String>, pub created_at: PrimitiveDateTime, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/reverse_lookup.rs
crates/diesel_models/src/reverse_lookup.rs
use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, Eq, PartialEq, )] #[diesel(table_name = reverse_lookup, primary_key(lookup_id), check_for_backend(diesel::pg::Pg))] pub struct ReverseLookup { /// Primary key. The key id. pub lookup_id: String, /// the `field` in KV database. Which is used to differentiate between two same keys pub sk_id: String, /// the value id. i.e the id you want to access KV table. pub pk_id: String, /// the source of insertion for reference pub source: String, pub updated_by: String, } #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, Eq, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = reverse_lookup)] pub struct ReverseLookupNew { pub lookup_id: String, pub pk_id: String, pub sk_id: String, pub source: String, pub updated_by: String, } impl From<ReverseLookupNew> for ReverseLookup { fn from(new: ReverseLookupNew) -> Self { Self { lookup_id: new.lookup_id, sk_id: new.sk_id, pk_id: new.pk_id, source: new.source, updated_by: new.updated_by, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/merchant_key_store.rs
crates/diesel_models/src/merchant_key_store.rs
use common_utils::{custom_serde, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::merchant_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantKeyStore { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Insertable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store)] pub struct MerchantKeyStoreNew { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, pub created_at: PrimitiveDateTime, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, AsChangeset, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store)] pub struct MerchantKeyStoreUpdateInternal { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/tokenization.rs
crates/diesel_models/src/tokenization.rs
#[cfg(feature = "v2")] use common_utils::id_type; #[cfg(feature = "v2")] use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; #[cfg(feature = "v2")] use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use time::PrimitiveDateTime; #[cfg(feature = "v2")] use crate::schema_v2::tokenization; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Identifiable, Insertable, Queryable)] #[diesel(table_name = tokenization)] pub struct Tokenization { pub id: id_type::GlobalTokenId, pub merchant_id: id_type::MerchantId, pub customer_id: id_type::GlobalCustomerId, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub locker_id: String, pub flag: common_enums::enums::TokenizationFlag, pub version: common_enums::enums::ApiVersion, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = tokenization)] pub struct TokenizationNew { pub id: id_type::GlobalTokenId, pub merchant_id: id_type::MerchantId, pub customer_id: id_type::GlobalCustomerId, pub locker_id: String, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub version: common_enums::enums::ApiVersion, pub flag: common_enums::enums::TokenizationFlag, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = tokenization)] pub struct TokenizationUpdateInternal { pub updated_at: PrimitiveDateTime, pub flag: Option<common_enums::enums::TokenizationFlag>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/api_keys.rs
crates/diesel_models/src/query/api_keys.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, ApiKeyUpdateInternal, HashedApiKey}, errors, schema::api_keys::dsl, PgPooledConn, StorageResult, }; impl ApiKeyNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ApiKey> { generics::generic_insert(conn, self).await } } impl ApiKey { pub async fn update_by_merchant_id_key_id( conn: &PgPooledConn, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key_update: ApiKeyUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::key_id.eq(key_id.to_owned())), ApiKeyUpdateInternal::from(api_key_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => { Err(error.attach_printable("API key with the given key ID does not exist")) } errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::key_id.eq(key_id.to_owned())), ) .await } _ => Err(error), }, result => result, } } pub async fn revoke_by_merchant_id_key_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::key_id.eq(key_id.to_owned())), ) .await } pub async fn find_optional_by_merchant_id_key_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::key_id.eq(key_id.to_owned())), ) .await } pub async fn find_optional_by_hashed_api_key( conn: &PgPooledConn, hashed_api_key: HashedApiKey, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::hashed_api_key.eq(hashed_api_key), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), limit, offset, Some(dsl::created_at.asc()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/locker_mock_up.rs
crates/diesel_models/src/query/locker_mock_up.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ locker_mock_up::{LockerMockUp, LockerMockUpNew}, schema::locker_mock_up::dsl, PgPooledConn, StorageResult, }; impl LockerMockUpNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<LockerMockUp> { generics::generic_insert(conn, self).await } } impl LockerMockUp { pub async fn find_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::card_id.eq(card_id.to_owned()), ) .await } pub async fn delete_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::card_id.eq(card_id.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/user.rs
crates/diesel_models/src/query/user.rs
use common_utils::pii; use diesel::{associations::HasTable, ExpressionMethods}; pub mod sample_data; pub mod theme; use crate::{ query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult, }; impl UserNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<User> { generics::generic_insert(conn, self).await } } impl User { pub async fn find_by_user_email( conn: &PgPooledConn, user_email: &pii::Email, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, users_dsl::email.eq(user_email.to_owned()), ) .await } pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, users_dsl::user_id.eq(user_id.to_owned()), ) .await } pub async fn update_by_user_id( conn: &PgPooledConn, user_id: &str, user_update: UserUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, users_dsl::user_id.eq(user_id.to_owned()), UserUpdateInternal::from(user_update), ) .await } pub async fn update_by_user_email( conn: &PgPooledConn, user_email: &pii::Email, user_update: UserUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, users_dsl::email.eq(user_email.to_owned()), UserUpdateInternal::from(user_update), ) .await } pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, users_dsl::user_id.eq(user_id.to_owned()), ) .await } pub async fn find_users_by_user_ids( conn: &PgPooledConn, user_ids: Vec<String>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >(conn, users_dsl::user_id.eq_any(user_ids), None, None, None) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/blocklist_fingerprint.rs
crates/diesel_models/src/query/blocklist_fingerprint.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}, schema::blocklist_fingerprint::dsl, PgPooledConn, StorageResult, }; impl BlocklistFingerprintNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistFingerprint> { generics::generic_insert(conn, self).await } } impl BlocklistFingerprint { pub async fn find_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/blocklist.rs
crates/diesel_models/src/query/blocklist.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist::{Blocklist, BlocklistNew}, schema::blocklist::dsl, PgPooledConn, StorageResult, }; impl BlocklistNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> { generics::generic_insert(conn, self).await } } impl Blocklist { pub async fn find_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } pub async fn list_by_merchant_id_data_kind( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::data_kind.eq(data_kind.to_owned())), Some(limit), Some(offset), Some(dsl::created_at.desc()), ) .await } pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn delete_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/payment_attempt.rs
crates/diesel_models/src/query/payment_attempt.rs
#[cfg(feature = "v1")] use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; #[cfg(feature = "v1")] use diesel::Table; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use super::generics; #[cfg(feature = "v1")] 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}, errors::DatabaseError, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal}, query::generics::db_metrics, PgPooledConn, StorageResult, }; impl PaymentAttemptNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> { generics::generic_insert(conn, self).await } } impl PaymentAttempt { #[cfg(feature = "v1")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payment_attempt: PaymentAttemptUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt).populate_derived_fields(&self), ) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[cfg(feature = "v2")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payment_attempt: PaymentAttemptUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(self.id.to_owned()), payment_attempt) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[cfg(feature = "v1")] pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_connector_transaction_id_payment_id_merchant_id( conn: &PgPooledConn, connector_transaction_id: &common_utils::types::ConnectorTransactionId, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::connector_transaction_id .eq(connector_transaction_id.get_id().to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_last_successful_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(enums::AttemptStatus::Charged)), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v1")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and( dsl::status .eq(enums::AttemptStatus::Charged) .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), ), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v2")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id.eq(payment_id.to_owned()).and( dsl::status .eq(enums::AttemptStatus::Charged) .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), ), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, ) -> StorageResult<Self> { let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( connector_txn_id.to_string(), ); let connector_transaction_id = txn_id .get_txn_id(txn_data.as_ref()) .change_context(DatabaseError::Others) .attach_printable_lazy(|| { format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})") })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_profile_id_connector_transaction_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_txn_id: &str, ) -> StorageResult<Self> { let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( connector_txn_id.to_string(), ); let connector_transaction_id = txn_id .get_txn_id(txn_data.as_ref()) .change_context(DatabaseError::Others) .attach_printable_lazy(|| { format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})") })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_payment_id.eq(connector_transaction_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalAttemptId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } #[cfg(feature = "v2")] pub async fn find_by_payment_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payment_id.eq(payment_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_preprocessing_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, preprocessing_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::preprocessing_step_id.eq(preprocessing_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id.eq(payment_id.to_owned()).and( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } #[cfg(feature = "v1")] pub async fn get_filters_for_payments( conn: &PgPooledConn, pi: &[PaymentIntent], merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<( Vec<String>, Vec<enums::Currency>, Vec<IntentStatus>, Vec<enums::PaymentMethod>, Vec<enums::PaymentMethodType>, Vec<enums::AuthenticationType>, )> { let active_attempts: Vec<String> = pi .iter() .map(|payment_intent| payment_intent.clone().active_attempt_id) .collect(); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::attempt_id.eq_any(active_attempts)); let intent_status: Vec<IntentStatus> = pi .iter() .map(|payment_intent| payment_intent.status) .collect::<HashSet<IntentStatus>>() .into_iter() .collect(); let filter_connector = filter .clone() .select(dsl::connector) .distinct() .get_results_async::<Option<String>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by connector")? .into_iter() .flatten() .collect::<Vec<String>>(); let filter_currency = filter .clone() .select(dsl::currency) .distinct() .get_results_async::<Option<enums::Currency>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by currency")? .into_iter() .flatten() .collect::<Vec<enums::Currency>>(); let filter_payment_method = filter .clone() .select(dsl::payment_method) .distinct() .get_results_async::<Option<enums::PaymentMethod>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payment method")? .into_iter() .flatten() .collect::<Vec<enums::PaymentMethod>>(); let filter_payment_method_type = filter .clone() .select(dsl::payment_method_type) .distinct() .get_results_async::<Option<enums::PaymentMethodType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payment method type")? .into_iter() .flatten() .collect::<Vec<enums::PaymentMethodType>>(); let filter_authentication_type = filter .clone() .select(dsl::authentication_type) .distinct() .get_results_async::<Option<enums::AuthenticationType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by authentication type")? .into_iter() .flatten() .collect::<Vec<enums::AuthenticationType>>(); Ok(( filter_connector, filter_currency, intent_status, filter_payment_method, filter_payment_method_type, filter_authentication_type, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<String>>, payment_method_type: Option<Vec<enums::PaymentMethod>>, payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<enums::CardNetwork>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); if let Some(connectors) = connector { filter = filter.filter(dsl::connector.eq_any(connectors)); } if let Some(payment_method_types) = payment_method_type { filter = filter.filter(dsl::payment_method_type_v2.eq_any(payment_method_types)); } if let Some(payment_method_subtypes) = payment_method_subtype { filter = filter.filter(dsl::payment_method_subtype.eq_any(payment_method_subtypes)); } if let Some(authentication_types) = authentication_type { filter = filter.filter(dsl::authentication_type.eq_any(authentication_types)); } if let Some(merchant_connector_ids) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_ids)); } if let Some(card_networks) = card_network { filter = filter.filter(dsl::card_network.eq_any(card_networks)); } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); // TODO: Remove these logs after debugging the issue for delay in count query let start_time = std::time::Instant::now(); router_env::logger::debug!("Executing count query start_time: {:?}", start_time); let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments"); let duration = start_time.elapsed(); router_env::logger::debug!("Completed count query in {:?}", duration); result } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<String>>, payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<enums::CardNetwork>>, card_discovery: Option<Vec<enums::CardDiscovery>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); if let Some(connector) = connector { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(payment_method) = payment_method { filter = filter.filter(dsl::payment_method.eq_any(payment_method)); } if let Some(payment_method_type) = payment_method_type { filter = filter.filter(dsl::payment_method_type.eq_any(payment_method_type)); } if let Some(authentication_type) = authentication_type { filter = filter.filter(dsl::authentication_type.eq_any(authentication_type)); } if let Some(merchant_connector_id) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } if let Some(card_network) = card_network { filter = filter.filter(dsl::card_network.eq_any(card_network)) } if let Some(card_discovery) = card_discovery { filter = filter.filter(dsl::card_discovery.eq_any(card_discovery)) } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); // TODO: Remove these logs after debugging the issue for delay in count query let start_time = std::time::Instant::now(); router_env::logger::debug!("Executing count query start_time: {:?}", start_time); let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments"); let duration = start_time.elapsed(); router_env::logger::debug!("Completed count query in {:?}", duration); result } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/fraud_check.rs
crates/diesel_models/src/query/fraud_check.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use crate::{ errors, fraud_check::*, query::generics, schema::fraud_check::dsl, PgPooledConn, StorageResult, }; impl FraudCheckNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FraudCheck> { generics::generic_insert(conn, self).await } } impl FraudCheck { pub async fn update_with_attempt_id( self, conn: &PgPooledConn, fraud_check: FraudCheckUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), FraudCheckUpdateInternal::from(fraud_check), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn get_with_payment_id( conn: &PgPooledConn, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } pub async fn get_with_payment_id_if_present( conn: &PgPooledConn, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/callback_mapper.rs
crates/diesel_models/src/query/callback_mapper.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ callback_mapper::CallbackMapper, schema::callback_mapper::dsl, PgPooledConn, StorageResult, }; impl CallbackMapper { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/dynamic_routing_stats.rs
crates/diesel_models/src/query/dynamic_routing_stats.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use super::generics; use crate::{ dynamic_routing_stats::{ DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate, }, errors, schema::dynamic_routing_stats::dsl, PgPooledConn, StorageResult, }; impl DynamicRoutingStatsNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DynamicRoutingStats> { generics::generic_insert(conn, self).await } } impl DynamicRoutingStats { pub async fn find_optional_by_attempt_id_merchant_id( conn: &PgPooledConn, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ) .await } pub async fn update( conn: &PgPooledConn, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, dynamic_routing_stat: DynamicRoutingStatsUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, DynamicRoutingStatsUpdate, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), dynamic_routing_stat, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating dynamic_routing_stats entry") }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/address.rs
crates/diesel_models/src/query/address.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, errors, schema::address::dsl, PgPooledConn, StorageResult, }; impl AddressNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Address> { generics::generic_insert(conn, self).await } } impl Address { pub async fn find_by_address_id(conn: &PgPooledConn, address_id: &str) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, address_id.to_owned()) .await } pub async fn update_by_address_id( conn: &PgPooledConn, address_id: String, address: AddressUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, address_id.clone(), address, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => { Err(error.attach_printable("Address with the given ID doesn't exist")) } errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, address_id.clone(), ) .await } _ => Err(error), }, result => result, } } pub async fn update( self, conn: &PgPooledConn, address_update_internal: AddressUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::address_id.eq(self.address_id.clone()), address_update_internal, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn delete_by_address_id( conn: &PgPooledConn, address_id: &str, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::address_id.eq(address_id.to_owned()), ) .await } pub async fn update_by_merchant_id_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, address: AddressUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::customer_id.eq(customer_id.to_owned())), address, ) .await } pub async fn find_by_merchant_id_payment_id_address_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, address_id: &str, ) -> StorageResult<Self> { match generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::address_id.eq(address_id.to_owned())), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, address_id.to_owned(), ) .await } _ => Err(error), }, result => result, } } pub async fn find_optional_by_address_id( conn: &PgPooledConn, address_id: &str, ) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, address_id.to_owned(), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/customers.rs
crates/diesel_models/src/query/customers.rs
use common_utils::id_type; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; #[cfg(feature = "v1")] use crate::schema::customers::dsl; #[cfg(feature = "v2")] use crate::schema_v2::customers::dsl; use crate::{ customers::{Customer, CustomerNew, CustomerUpdateInternal}, errors, PgPooledConn, StorageResult, }; impl CustomerNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> { generics::generic_insert(conn, self).await } } pub struct CustomerListConstraints { pub limit: i64, pub offset: Option<i64>, pub customer_id: Option<id_type::CustomerId>, pub time_range: Option<common_utils::types::TimeRange>, } impl Customer { #[cfg(feature = "v2")] pub async fn update_by_id( conn: &PgPooledConn, id: id_type::GlobalCustomerId, customer: CustomerUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, id.clone(), customer, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id).await } _ => Err(error), }, result => result, } } #[cfg(feature = "v2")] pub async fn find_by_global_id( conn: &PgPooledConn, id: &id_type::GlobalCustomerId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } #[cfg(feature = "v1")] pub async fn get_customer_count_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, customer_list_constraints: CustomerListConstraints, ) -> StorageResult<usize> { if let Some(customer_id) = customer_list_constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::customer_id.eq(customer_id)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else if let Some(time_range) = customer_list_constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else { generics::generic_count::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } } #[cfg(feature = "v2")] pub async fn get_customer_count_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, customer_list_constraints: CustomerListConstraints, ) -> StorageResult<usize> { if let Some(customer_id) = customer_list_constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::merchant_reference_id.eq(customer_id)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else if let Some(time_range) = customer_list_constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else { generics::generic_count::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } } #[cfg(feature = "v1")] pub async fn list_customers_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { if let Some(customer_id) = constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::customer_id.eq(customer_id)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else if let Some(time_range) = constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else { let predicate = dsl::merchant_id.eq(merchant_id.clone()); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } } #[cfg(feature = "v2")] pub async fn list_customers_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { if let Some(customer_id) = constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::merchant_reference_id.eq(customer_id)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else if let Some(time_range) = constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else { let predicate = dsl::merchant_id.eq(merchant_id.clone()); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } } #[cfg(feature = "v2")] pub async fn find_optional_by_merchant_id_merchant_reference_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_reference_id.eq(customer_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_optional_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, (customer_id.to_owned(), merchant_id.to_owned()), ) .await } #[cfg(feature = "v1")] pub async fn update_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: CustomerUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, (customer_id.clone(), merchant_id.clone()), customer, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, (customer_id, merchant_id), ) .await } _ => Err(error), }, result => result, } } #[cfg(feature = "v1")] pub async fn delete_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, (customer_id.to_owned(), merchant_id.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/user_authentication_method.rs
crates/diesel_models/src/query/user_authentication_method.rs
use diesel::{associations::HasTable, ExpressionMethods}; use crate::{ query::generics, schema::user_authentication_methods::dsl, user_authentication_method::*, PgPooledConn, StorageResult, }; impl UserAuthenticationMethodNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserAuthenticationMethod> { generics::generic_insert(conn, self).await } } impl UserAuthenticationMethod { pub async fn get_user_authentication_method_by_id( conn: &PgPooledConn, id: &str, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } pub async fn list_user_authentication_methods_for_auth_id( conn: &PgPooledConn, auth_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::auth_id.eq(auth_id.to_owned()), None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn list_user_authentication_methods_for_owner_id( conn: &PgPooledConn, owner_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::owner_id.eq(owner_id.to_owned()), None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn update_user_authentication_method( conn: &PgPooledConn, id: &str, user_authentication_method_update: UserAuthenticationMethodUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::id.eq(id.to_owned()), OrgAuthenticationMethodUpdateInternal::from(user_authentication_method_update), ) .await } pub async fn list_user_authentication_methods_for_email_domain( conn: &PgPooledConn, email_domain: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::email_domain.eq(email_domain.to_owned()), None, None, Some(dsl::last_modified_at.asc()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/capture.rs
crates/diesel_models/src/query/capture.rs
use common_utils::types::ConnectorTransactionIdTrait; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ capture::{Capture, CaptureNew, CaptureUpdate, CaptureUpdateInternal}, errors, schema::captures::dsl, PgPooledConn, StorageResult, }; impl CaptureNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Capture> { generics::generic_insert(conn, self).await } } impl Capture { pub async fn find_by_capture_id(conn: &PgPooledConn, capture_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::capture_id.eq(capture_id.to_owned()), ) .await } pub async fn update_with_capture_id( self, conn: &PgPooledConn, capture: CaptureUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::capture_id.eq(self.capture_id.to_owned()), CaptureUpdateInternal::from(capture), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, conn: &PgPooledConn, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::authorized_attempt_id .eq(authorized_attempt_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, Some(dsl::created_at.asc()), ) .await } } impl ConnectorTransactionIdTrait for Capture { fn get_optional_connector_transaction_id(&self) -> Option<&String> { match self .connector_capture_id .as_ref() .map(|capture_id| capture_id.get_txn_id(self.processor_capture_data.as_ref())) .transpose() { Ok(capture_id) => capture_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self .connector_capture_id .as_ref() .map(|txn_id| txn_id.get_id()), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/payment_link.rs
crates/diesel_models/src/query/payment_link.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ payment_link::{PaymentLink, PaymentLinkNew}, schema::payment_link::dsl, PgPooledConn, StorageResult, }; impl PaymentLinkNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentLink> { generics::generic_insert(conn, self).await } } impl PaymentLink { pub async fn find_link_by_payment_link_id( conn: &PgPooledConn, payment_link_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_link_id.eq(payment_link_id.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/dispute.rs
crates/diesel_models/src/query/dispute.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; use crate::{ dispute::{Dispute, DisputeNew, DisputeUpdate, DisputeUpdateInternal}, errors, schema::dispute::dsl, PgPooledConn, StorageResult, }; impl DisputeNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Dispute> { generics::generic_insert(conn, self).await } } impl Dispute { pub async fn find_by_merchant_id_payment_id_connector_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::connector_dispute_id.eq(connector_dispute_id.to_owned())), ) .await } pub async fn find_by_merchant_id_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::dispute_id.eq(dispute_id.to_owned())), ) .await } pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } pub async fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::dispute_id.eq(self.dispute_id.to_owned()), DisputeUpdateInternal::from(dispute), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/process_tracker.rs
crates/diesel_models/src/query/process_tracker.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use router_env::{instrument, tracing}; use time::PrimitiveDateTime; use super::generics; use crate::{ enums, errors, process_tracker::{ ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate, ProcessTrackerUpdateInternal, }, schema::process_tracker::dsl, PgPooledConn, StorageResult, }; impl ProcessTrackerNew { #[instrument(skip(conn))] pub async fn insert_process(self, conn: &PgPooledConn) -> StorageResult<ProcessTracker> { generics::generic_insert(conn, self).await } } impl ProcessTracker { #[instrument(skip(conn))] pub async fn update( self, conn: &PgPooledConn, process: ProcessTrackerUpdate, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.clone(), ProcessTrackerUpdateInternal::from(process), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[instrument(skip(conn))] pub async fn update_process_status_by_ids( conn: &PgPooledConn, task_ids: Vec<String>, task_update: ProcessTrackerUpdate, ) -> StorageResult<usize> { generics::generic_update::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq_any(task_ids), ProcessTrackerUpdateInternal::from(task_update), ) .await } #[instrument(skip(conn))] pub async fn find_process_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, id.to_owned(), ) .await } #[instrument(skip(conn))] pub async fn find_processes_by_time_status( conn: &PgPooledConn, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, status: enums::ProcessTrackerStatus, limit: Option<i64>, version: enums::ApiVersion, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::schedule_time .between(time_lower_limit, time_upper_limit) .and(dsl::status.eq(status)) .and(dsl::version.eq(version)), limit, None, None, ) .await } #[instrument(skip(conn))] pub async fn find_processes_to_clean( conn: &PgPooledConn, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, runner: &str, limit: usize, ) -> StorageResult<Vec<Self>> { let mut x: Vec<Self> = generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::schedule_time .between(time_lower_limit, time_upper_limit) .and(dsl::status.eq(enums::ProcessTrackerStatus::ProcessStarted)) .and(dsl::runner.eq(runner.to_owned())), None, None, None, ) .await?; x.sort_by(|a, b| a.schedule_time.cmp(&b.schedule_time)); x.truncate(limit); Ok(x) } #[instrument(skip(conn))] pub async fn reinitialize_limbo_processes( conn: &PgPooledConn, ids: Vec<String>, schedule_time: PrimitiveDateTime, ) -> StorageResult<usize> { generics::generic_update::<<Self as HasTable>::Table, _, _>( conn, dsl::status .eq(enums::ProcessTrackerStatus::ProcessStarted) .and(dsl::id.eq_any(ids)), ( dsl::status.eq(enums::ProcessTrackerStatus::Processing), dsl::schedule_time.eq(schedule_time), ), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/payout_attempt.rs
crates/diesel_models/src/query/payout_attempt.rs
use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, query_dsl::methods::{DistinctDsl, FilterDsl, SelectDsl}, BoolExpressionMethods, ExpressionMethods, }; use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums, errors::DatabaseError, payout_attempt::{ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal, }, schema::{payout_attempt::dsl, payouts as payout_dsl}, Payouts, PgPooledConn, StorageResult, }; impl PayoutAttemptNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> { generics::generic_insert(conn, self).await } } impl PayoutAttempt { pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payout_attempt_update: PayoutAttemptUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::payout_attempt_id .eq(self.payout_attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PayoutAttemptUpdateInternal::from(payout_attempt_update), ) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn find_by_merchant_id_payout_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_payout_id.eq(connector_payout_id.to_owned())), ) .await } pub async fn find_by_merchant_id_merchant_order_reference_id( conn: &PgPooledConn, merchant_id_input: &common_utils::id_type::MerchantId, merchant_order_reference_id_input: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id_input.to_owned()).and( dsl::merchant_order_reference_id.eq(merchant_order_reference_id_input.to_owned()), ), ) .await } pub async fn update_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, payout: PayoutAttemptUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), PayoutAttemptUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn update_by_merchant_id_payout_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, payout: PayoutAttemptUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())), PayoutAttemptUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn get_filters_for_payouts( conn: &PgPooledConn, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<( Vec<String>, Vec<enums::Currency>, Vec<enums::PayoutStatus>, Vec<enums::PayoutType>, )> { let active_attempt_ids = payouts .iter() .map(|payout| { format!( "{}_{}", payout.payout_id.get_string_repr(), payout.attempt_count.clone() ) }) .collect::<Vec<String>>(); let active_payout_ids = payouts .iter() .map(|payout| payout.payout_id.to_owned()) .collect::<Vec<common_utils::id_type::PayoutId>>(); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::payout_attempt_id.eq_any(active_attempt_ids)); let payouts_filter = <Payouts as HasTable>::table() .filter(payout_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payout_dsl::payout_id.eq_any(active_payout_ids)); let payout_status: Vec<enums::PayoutStatus> = payouts .iter() .map(|payout| payout.status) .collect::<HashSet<enums::PayoutStatus>>() .into_iter() .collect(); let filter_connector = filter .clone() .select(dsl::connector) .distinct() .get_results_async::<Option<String>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by connector")? .into_iter() .flatten() .collect::<Vec<String>>(); let filter_currency = payouts_filter .clone() .select(payout_dsl::destination_currency) .distinct() .get_results_async::<enums::Currency>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by currency")? .into_iter() .collect::<Vec<enums::Currency>>(); let filter_payout_method = payouts_filter .clone() .select(payout_dsl::payout_type) .distinct() .get_results_async::<Option<enums::PayoutType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payout type")? .into_iter() .flatten() .collect::<Vec<enums::PayoutType>>(); Ok(( filter_connector, filter_currency, payout_status, filter_payout_method, )) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/organization.rs
crates/diesel_models/src/query/organization.rs
use common_utils::id_type; use diesel::{associations::HasTable, ExpressionMethods}; #[cfg(feature = "v1")] use crate::schema::organization::dsl::org_id as dsl_identifier; #[cfg(feature = "v2")] use crate::schema_v2::organization::dsl::id as dsl_identifier; use crate::{organization::*, query::generics, PgPooledConn, StorageResult}; impl OrganizationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Organization> { generics::generic_insert(conn, self).await } } impl Organization { pub async fn find_by_org_id( conn: &PgPooledConn, org_id: id_type::OrganizationId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl_identifier.eq(org_id), ) .await } pub async fn update_by_org_id( conn: &PgPooledConn, org_id: id_type::OrganizationId, update: OrganizationUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl_identifier.eq(org_id), OrganizationUpdateInternal::from(update), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/payment_intent.rs
crates/diesel_models/src/query/payment_intent.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; #[cfg(feature = "v1")] use crate::schema::payment_intent::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent::dsl; use crate::{ errors, payment_intent::{self, PaymentIntent, PaymentIntentNew}, PgPooledConn, StorageResult, }; impl PaymentIntentNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> { generics::generic_insert(conn, self).await } } impl PaymentIntent { #[cfg(feature = "v2")] pub async fn update( self, conn: &PgPooledConn, payment_intent_update: payment_intent::PaymentIntentUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.to_owned(), payment_intent_update, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(payment_intent) => Ok(payment_intent), } } #[cfg(feature = "v2")] pub async fn find_by_global_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } #[cfg(feature = "v1")] pub async fn update( self, conn: &PgPooledConn, payment_intent: payment_intent::PaymentIntentUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payment_id .eq(self.payment_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), payment_intent::PaymentIntentUpdateInternal::from(payment_intent), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(mut payment_intents) => payment_intents .pop() .ok_or(error_stack::report!(errors::DatabaseError::NotFound)), } } #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } // This query should be removed in the future because direct queries to the intent table without an intent ID are not allowed. // In an active-active setup, a lookup table should be implemented, and the merchant reference ID will serve as the idempotency key. #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_profile_id( conn: &PgPooledConn, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_optional_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/cards_info.rs
crates/diesel_models/src/query/cards_info.rs
use diesel::{associations::HasTable, ExpressionMethods}; use error_stack::report; use crate::{ cards_info::{CardInfo, UpdateCardInfo}, errors, query::generics, schema::cards_info::dsl, PgPooledConn, StorageResult, }; impl CardInfo { pub async fn find_by_iin(conn: &PgPooledConn, card_iin: &str) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, card_iin.to_owned(), ) .await } pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn update( conn: &PgPooledConn, card_iin: String, data: UpdateCardInfo, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, UpdateCardInfo, _, _>( conn, dsl::card_iin.eq(card_iin), data, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating card_info entry") }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/merchant_account.rs
crates/diesel_models/src/query/merchant_account.rs
#[cfg(feature = "v1")] use common_types::consts::API_VERSION; #[cfg(feature = "v1")] use diesel::BoolExpressionMethods; use diesel::{associations::HasTable, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::merchant_account::dsl; #[cfg(feature = "v2")] use crate::schema_v2::merchant_account::dsl; use crate::{ errors, merchant_account::{MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal}, PgPooledConn, StorageResult, }; impl MerchantAccountNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantAccount> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl MerchantAccount { pub async fn update( self, conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), merchant_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn update_with_specific_fields( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id.eq(identifier.to_owned()), merchant_account, ) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(identifier.to_owned()), ) .await } pub async fn find_by_publishable_key( conn: &PgPooledConn, publishable_key: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::publishable_key.eq(publishable_key.to_owned()), ) .await } pub async fn list_by_organization_id( conn: &PgPooledConn, organization_id: &common_utils::id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::organization_id .eq(organization_id.to_owned()) .and(dsl::version.eq(API_VERSION)), None, None, None, ) .await } pub async fn list_multiple_merchant_accounts( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq_any(merchant_ids.clone()), None, None, None, ) .await } pub async fn list_all_merchant_accounts( conn: &PgPooledConn, limit: u32, offset: Option<u32>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.ne_all(vec![""]), Some(i64::from(limit)), offset.map(i64::from), None, ) .await } pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.ne_all(vec![""]), merchant_account, ) .await } } #[cfg(feature = "v2")] impl MerchantAccount { pub async fn update( self, conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), merchant_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn update_with_specific_fields( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(identifier.to_owned()), merchant_account) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::id.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(identifier.to_owned()), ) .await } pub async fn find_by_publishable_key( conn: &PgPooledConn, publishable_key: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::publishable_key.eq(publishable_key.to_owned()), ) .await } pub async fn list_by_organization_id( conn: &PgPooledConn, organization_id: &common_utils::id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::organization_id.eq(organization_id.to_owned()), None, None, None, ) .await } pub async fn list_multiple_merchant_accounts( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >(conn, dsl::id.eq_any(merchant_ids), None, None, None) .await } pub async fn list_all_merchant_accounts( conn: &PgPooledConn, limit: u32, offset: Option<u32>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::id.ne_all(vec![""]), Some(i64::from(limit)), offset.map(i64::from), None, ) .await } pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::id.ne_all(vec![""]), merchant_account, ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/user_key_store.rs
crates/diesel_models/src/query/user_key_store.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ schema::user_key_store::dsl, user_key_store::{UserKeyStore, UserKeyStoreNew}, PgPooledConn, StorageResult, }; impl UserKeyStoreNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> { generics::generic_insert(conn, self).await } } impl UserKeyStore { pub async fn get_all_user_key_stores( conn: &PgPooledConn, from: u32, limit: u32, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::user_id.ne_all(vec!["".to_string()]), Some(limit.into()), Some(from.into()), None, ) .await } pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id.eq(user_id.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/generic_link.rs
crates/diesel_models/src/query/generic_link.rs
use common_utils::{errors, ext_traits::ValueExt, link_utils::GenericLinkStatus}; use diesel::{associations::HasTable, ExpressionMethods}; use error_stack::{report, Report, ResultExt}; use super::generics; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; impl GenericLinkNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GenericLinkState> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } pub async fn insert_pm_collect_link( self, conn: &PgPooledConn, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } } impl GenericLink { pub async fn find_generic_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<GenericLinkState> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } pub async fn find_pm_collect_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } pub async fn find_payout_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PayoutLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } } impl PayoutLink { pub async fn update_payout_link( self, conn: &PgPooledConn, payout_link_update: PayoutLinkUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::link_id.eq(self.link_id.to_owned()), GenericLinkUpdateInternal::from(payout_link_update), ) .await .and_then(|mut payout_links| { payout_links .pop() .ok_or(error_stack::report!(db_errors::DatabaseError::NotFound)) }) .or_else(|error| match error.current_context() { db_errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }) } } impl TryFrom<GenericLink> for GenericLinkState { type Error = Report<errors::ParsingError>; fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let link_data = match db_val.link_type { common_enums::GenericLinkType::PaymentMethodCollect => { let link_data = db_val .link_data .parse_value("PaymentMethodCollectLinkData")?; GenericLinkData::PaymentMethodCollect(link_data) } common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; GenericLinkData::PayoutLink(link_data) } }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status: db_val.link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } } impl TryFrom<GenericLink> for PaymentMethodCollectLink { type Error = Report<errors::ParsingError>; fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PaymentMethodCollect => { let link_data = db_val .link_data .parse_value("PaymentMethodCollectLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PaymentMethodCollect(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!( "Invalid status for PaymentMethodCollectLink - {:?}", db_val.link_status ) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!( "Invalid link_type for PaymentMethodCollectLink - {}", db_val.link_type ) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } } impl TryFrom<GenericLink> for PayoutLink { type Error = Report<errors::ParsingError>; fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: common_utils::id_type::PayoutId::try_from(std::borrow::Cow::Owned( db_val.primary_reference, )) .change_context(errors::ParsingError::UnknownError) .attach_printable("Failed to parse PayoutId from primary_reference string")?, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/subscription.rs
crates/diesel_models/src/query/subscription.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use super::generics; use crate::{ errors, schema::subscription::dsl, subscription::{Subscription, SubscriptionNew, SubscriptionUpdate}, PgPooledConn, StorageResult, }; impl SubscriptionNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Subscription> { generics::generic_insert(conn, self).await } } impl Subscription { pub async fn find_by_merchant_id_subscription_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, id: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::id.eq(id.to_owned())), ) .await } pub async fn update_subscription_entry( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, id: String, subscription_update: SubscriptionUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, SubscriptionUpdate, _, _, >( conn, dsl::id .eq(id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), subscription_update, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating subscription entry") }) } pub async fn list_by_merchant_id_profile_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, limit: Option<i64>, offset: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), limit, offset, Some(dsl::created_at.desc()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/user_role.rs
crates/diesel_models/src/query/user_role.rs
use async_bb8_diesel::AsyncRunQueryDsl; use common_enums::EntityType; use common_utils::id_type; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use crate::{ enums::{UserRoleVersion, UserStatus}, errors, query::generics, schema::user_roles::dsl, user_role::*, PgPooledConn, StorageResult, }; impl UserRoleNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> { generics::generic_insert(conn, self).await } } impl UserRole { fn check_user_in_lineage( tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { // Checking in user roles, for a user in token hierarchy, only one of the relations will be true: // either tenant level, org level, merchant level, or profile level // Tenant-level: (tenant_id = ? && org_id = null && merchant_id = null && profile_id = null) // Org-level: (org_id = ? && merchant_id = null && profile_id = null) // Merchant-level: (org_id = ? && merchant_id = ? && profile_id = null) // Profile-level: (org_id = ? && merchant_id = ? && profile_id = ?) Box::new( // Tenant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .or( // Org-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ) .or( // Merchant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.eq(merchant_id.clone())) .and(dsl::profile_id.is_null()), ) .or( // Profile-level condition dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ), ) } pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = Self::check_user_in_lineage( tenant_id, Some(org_id), Some(merchant_id), Some(profile_id), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await } fn check_user_in_lineage_with_entity_type( tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { // Checking in user roles, for a user in token hierarchy, only one of the relations will be true: // either tenant level, org level, merchant level, or profile level // Tenant-level: (tenant_id = ? && org_id = null && merchant_id = null && profile_id = null) // Org-level: (org_id = ? && entity_type = organization) // Merchant-level: (org_id = ? && merchant_id = ? && entity_id = merchant) // Profile-level: (org_id = ? && merchant_id = ? && profile_id = ? && entity_type = profile) Box::new( // Tenant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::entity_type.eq(EntityType::Tenant)) .or( // Org-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::entity_type.eq(EntityType::Organization)), ) .or( // Merchant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.eq(merchant_id.clone())) .and(dsl::entity_type.eq(EntityType::Merchant)), ) .or( // Profile-level condition dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)) .and(dsl::entity_type.eq(EntityType::Profile)), ), ) } pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id_with_entity_type( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = Self::check_user_in_lineage_with_entity_type( tenant_id, Some(org_id), Some(merchant_id), Some(profile_id), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await } #[allow(clippy::too_many_arguments)] pub async fn update_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, update: UserRoleUpdate, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .or( // Org-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ) .or( // Merchant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.eq(merchant_id.clone())) .and(dsl::profile_id.is_null()), ) .or( // Profile-level condition dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, UserRoleUpdateInternal, _, _, >(conn, predicate, update.into()) .await } pub async fn delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = Self::check_user_in_lineage( tenant_id, Some(org_id), Some(merchant_id), Some(profile_id), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn, predicate) .await } #[allow(clippy::too_many_arguments)] pub async fn generic_user_roles_list_for_user( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, entity_id: Option<String>, status: Option<UserStatus>, version: Option<UserRoleVersion>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id))) .into_boxed(); if let Some(org_id) = org_id { query = query.filter(dsl::org_id.eq(org_id)); } if let Some(merchant_id) = merchant_id { query = query.filter(dsl::merchant_id.eq(merchant_id)); } if let Some(profile_id) = profile_id { query = query.filter(dsl::profile_id.eq(profile_id)); } if let Some(entity_id) = entity_id { query = query.filter(dsl::entity_id.eq(entity_id)); } if let Some(version) = version { query = query.filter(dsl::version.eq(version)); } if let Some(status) = status { query = query.filter(dsl::status.eq(status)); } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } #[allow(clippy::too_many_arguments)] pub async fn generic_user_roles_list_for_org_and_extra( conn: &PgPooledConn, user_id: Option<String>, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, version: Option<UserRoleVersion>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id))) .into_boxed(); if let Some(user_id) = user_id { query = query.filter(dsl::user_id.eq(user_id)); } if let Some(merchant_id) = merchant_id { query = query.filter(dsl::merchant_id.eq(merchant_id)); } if let Some(profile_id) = profile_id { query = query.filter(dsl::profile_id.eq(profile_id)); } if let Some(version) = version { query = query.filter(dsl::version.eq(version)); } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } pub async fn list_user_roles_by_user_id_across_tenants( conn: &PgPooledConn, user_id: String, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::user_id.eq(user_id)) .into_boxed(); if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/invoice.rs
crates/diesel_models/src/query/invoice.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ invoice::{Invoice, InvoiceNew, InvoiceUpdate}, schema::invoice::dsl, PgPooledConn, StorageResult, }; impl InvoiceNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Invoice> { generics::generic_insert(conn, self).await } } impl Invoice { pub async fn find_invoice_by_id_invoice_id( conn: &PgPooledConn, id: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } pub async fn update_invoice_entry( conn: &PgPooledConn, id: String, invoice_update: InvoiceUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(id.to_owned()), invoice_update) .await } pub async fn list_invoices_by_subscription_id( conn: &PgPooledConn, subscription_id: String, limit: Option<i64>, offset: Option<i64>, order_by_ascending_order: bool, ) -> StorageResult<Vec<Self>> { if order_by_ascending_order { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::subscription_id.eq(subscription_id.to_owned()), limit, offset, Some(dsl::created_at.asc()), ) .await } else { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::subscription_id.eq(subscription_id.to_owned()), limit, offset, Some(dsl::created_at.desc()), ) .await } } pub async fn get_invoice_by_subscription_id_connector_invoice_id( conn: &PgPooledConn, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::subscription_id .eq(subscription_id.to_owned()) .and(dsl::connector_invoice_id.eq(connector_invoice_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/relay.rs
crates/diesel_models/src/query/relay.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ errors, relay::{Relay, RelayNew, RelayUpdateInternal}, schema::relay::dsl, PgPooledConn, StorageResult, }; impl RelayNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Relay> { generics::generic_insert(conn, self).await } } impl Relay { pub async fn update( self, conn: &PgPooledConn, relay: RelayUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(self.id.to_owned()), relay) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::RelayId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } pub async fn find_by_profile_id_connector_reference_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_reference_id.eq(connector_reference_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/generics.rs
crates/diesel_models/src/query/generics.rs
use std::fmt::Debug; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, debug_query, dsl::{count_star, Find, IsNotNull, Limit}, helper_types::{Filter, IntoBoxed}, insertable::CanInsertInSingleQuery, pg::{Pg, PgConnection}, query_builder::{ AsChangeset, AsQuery, DeleteStatement, InsertStatement, IntoUpdateTarget, QueryFragment, QueryId, UpdateStatement, }, query_dsl::{ methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl, SelectDsl}, LoadQuery, RunQueryDsl, }, result::Error as DieselError, Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table, }; use error_stack::{report, ResultExt}; use router_env::logger; use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult}; pub mod db_metrics { #[derive(Debug)] pub enum DatabaseOperation { FindOne, Filter, Update, Insert, Delete, DeleteWithResult, UpdateWithResults, UpdateOne, Count, } #[inline] pub async fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U where Fut: std::future::Future<Output = U>, { let start = std::time::Instant::now(); let output = future.await; let time_elapsed = start.elapsed(); let table_name = std::any::type_name::<T>().rsplit("::").nth(1); let attributes = router_env::metric_attributes!( ("table", table_name.unwrap_or("undefined")), ("operation", format!("{:?}", operation)) ); crate::metrics::DATABASE_CALLS_COUNT.add(1, attributes); crate::metrics::DATABASE_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes); output } } use db_metrics::*; pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R> where T: HasTable<Table = T> + Table + 'static + Debug, V: Debug + Insertable<T>, <T as QuerySource>::FromClause: QueryFragment<Pg> + Debug, <V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static, InsertStatement<T, <V as Insertable<T>>::Values>: AsQuery + LoadQuery<'static, PgConnection, R> + Send, R: Send + 'static, { let debug_values = format!("{values:?}"); let query = diesel::insert_into(<T as HasTable>::table()).values(values); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); match track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => { Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } .attach_printable_lazy(|| format!("Error while inserting {debug_values}")) } pub async fn generic_update<T, V, P>( conn: &PgPooledConn, predicate: P, values: V, ) -> StorageResult<usize> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug, Filter<T, P>: IntoUpdateTarget, UpdateStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static, { let debug_values = format!("{values:?}"); let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update) .await .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating {debug_values}")) } pub async fn generic_update_with_results<T, V, P, R>( conn: &PgPooledConn, predicate: P, values: V, ) -> StorageResult<Vec<R>> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static, Filter<T, P>: IntoUpdateTarget + 'static, UpdateStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone, R: Send + 'static, // For cloning query (UpdateStatement) <Filter<T, P> as HasTable>::Table: Clone, <Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone, <V as AsChangeset>::Changeset: Clone, <<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone, { let debug_values = format!("{values:?}"); let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values); match track_database_call::<T, _, _>( query.to_owned().get_results_async(conn), DatabaseOperation::UpdateWithResults, ) .await { Ok(result) => { logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); Ok(result) } Err(DieselError::QueryBuilderError(_)) => { Err(report!(errors::DatabaseError::NoFieldsToUpdate)) .attach_printable_lazy(|| format!("Error while updating {debug_values}")) } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), Err(error) => Err(error) .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), } } pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>( conn: &PgPooledConn, predicate: P, values: V, ) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static, Filter<T, P>: IntoUpdateTarget + 'static, UpdateStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send, R: Send + 'static, // For cloning query (UpdateStatement) <Filter<T, P> as HasTable>::Table: Clone, <Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone, <V as AsChangeset>::Changeset: Clone, <<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone, { generic_update_with_results::<<T as HasTable>::Table, _, _, _>(conn, predicate, values) .await .map(|mut vec_r| { if vec_r.is_empty() { Err(errors::DatabaseError::NotFound) } else if vec_r.len() != 1 { Err(errors::DatabaseError::Others) } else { vec_r.pop().ok_or(errors::DatabaseError::Others) } .attach_printable("Maybe not queried using a unique key") })? } pub async fn generic_update_by_id<T, V, Pk, R>( conn: &PgPooledConn, id: Pk, values: V, ) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + Debug, Find<T, Pk>: IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, UpdateStatement< <Find<T, Pk> as HasTable>::Table, <Find<T, Pk> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, Find<T, Pk>: LimitDsl, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, R: Send + 'static, Pk: Clone + Debug, // For cloning query (UpdateStatement) <Find<T, Pk> as HasTable>::Table: Clone, <Find<T, Pk> as IntoUpdateTarget>::WhereClause: Clone, <V as AsChangeset>::Changeset: Clone, <<Find<T, Pk> as HasTable>::Table as QuerySource>::FromClause: Clone, { let debug_values = format!("{values:?}"); let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values); match track_database_call::<T, _, _>( query.to_owned().get_result_async(conn), DatabaseOperation::UpdateOne, ) .await { Ok(result) => { logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); Ok(result) } Err(DieselError::QueryBuilderError(_)) => { Err(report!(errors::DatabaseError::NoFieldsToUpdate)) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")) } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), Err(error) => Err(error) .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), } } pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: IntoUpdateTarget, DeleteStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, >: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static, { let query = diesel::delete(<T as HasTable>::table().filter(predicate)); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting") .and_then(|result| match result { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(true) } 0 => { Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted")) } _ => Ok(true), // n is usize, rustc requires this for exhaustive check }) } pub async fn generic_delete_one_with_result<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: IntoUpdateTarget, DeleteStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + Clone + 'static, { let query = diesel::delete(<T as HasTable>::table().filter(predicate)); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>( query.get_results_async(conn), DatabaseOperation::DeleteWithResult, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting") .and_then(|result| { result.first().cloned().ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Object to be deleted does not exist") }) }) } async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, Pk: Clone + Debug, R: Send + 'static, { let query = <T as HasTable>::table().find(id.to_owned()); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); match track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne).await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } .attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}")) } pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, Pk: Clone + Debug, R: Send + 'static, { generic_find_by_id_core::<T, _, _>(conn, id).await } pub async fn generic_find_by_id_optional<T, Pk, R>( conn: &PgPooledConn, id: Pk, ) -> StorageResult<Option<R>> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, <T as HasTable>::Table: FindDsl<Pk>, Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, Pk: Clone + Debug, R: Send + 'static, { to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await) } async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { let query = <T as HasTable>::table().filter(predicate); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne) .await .map_err(|err| match err { DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound), _ => report!(err).change_context(errors::DatabaseError::Others), }) .attach_printable("Error finding record by predicate") } pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { generic_find_one_core::<T, _, _>(conn, predicate).await } pub async fn generic_find_one_optional<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<Option<R>> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await) } pub(super) async fn generic_filter<T, P, O, R>( conn: &PgPooledConn, predicate: P, limit: Option<i64>, offset: Option<i64>, order: Option<O>, ) -> StorageResult<Vec<R>> where T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + GetPrimaryKey + 'static, IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>> + FilterDsl<IsNotNull<T::PK>, Output = IntoBoxed<'static, T, Pg>> + LimitDsl<Output = IntoBoxed<'static, T, Pg>> + OffsetDsl<Output = IntoBoxed<'static, T, Pg>> + OrderDsl<O, Output = IntoBoxed<'static, T, Pg>> + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send, O: Expression, R: Send + 'static, { let mut query = T::table().into_boxed(); query = query .filter(predicate) .filter(T::table().get_primary_key().is_not_null()); if let Some(limit) = limit { query = query.limit(limit); } if let Some(offset) = offset { query = query.offset(offset); } if let Some(order) = order { query = query.order(order); } logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by predicate") } pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize> where T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static, Filter<T, P>: SelectDsl<count_star>, diesel::dsl::Select<Filter<T, P>, count_star>: LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static, { let query = <T as HasTable>::table() .filter(predicate) .select(count_star()); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); let count_i64: i64 = track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error counting records by predicate")?; let count_usize = usize::try_from(count_i64).map_err(|_| { report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize") })?; Ok(count_usize) } fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> { match arg { Ok(value) => Ok(Some(value)), Err(err) => match err.current_context() { errors::DatabaseError::NotFound => Ok(None), _ => Err(err), }, } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/file.rs
crates/diesel_models/src/query/file.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ errors, file::{FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal}, schema::file_metadata::dsl, PgPooledConn, StorageResult, }; impl FileMetadataNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FileMetadata> { generics::generic_insert(conn, self).await } } impl FileMetadata { pub async fn find_by_merchant_id_file_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::file_id.eq(file_id.to_owned())), ) .await } pub async fn delete_by_merchant_id_file_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::file_id.eq(file_id.to_owned())), ) .await } pub async fn update( self, conn: &PgPooledConn, file_metadata: FileMetadataUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::file_id.eq(self.file_id.to_owned()), FileMetadataUpdateInternal::from(file_metadata), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/merchant_connector_account.rs
crates/diesel_models/src/query/merchant_connector_account.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::merchant_connector_account::dsl; #[cfg(feature = "v2")] use crate::schema_v2::merchant_connector_account::dsl; use crate::{ errors, merchant_connector_account::{ MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal, }, PgPooledConn, StorageResult, }; impl MerchantConnectorAccountNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantConnectorAccount> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl MerchantConnectorAccount { pub async fn update( self, conn: &PgPooledConn, merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.merchant_connector_id.to_owned(), merchant_connector_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn delete_by_merchant_id_merchant_connector_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_connector_id.eq(merchant_connector_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_label.eq(connector_label.to_owned())), ) .await } pub async fn find_by_profile_id_connector_name( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_name.eq(connector_name.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_name( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_name.eq(connector_name.to_owned())), None, None, None, ) .await } pub async fn find_by_merchant_id_merchant_connector_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_connector_id.eq(merchant_connector_id.to_owned())), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, ) -> StorageResult<Vec<Self>> { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } else { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::disabled.eq(false)), None, None, None, ) .await } } pub async fn list_enabled_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_type: common_enums::ConnectorType, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::disabled.eq(false)) .and(dsl::connector_type.eq(connector_type)), None, None, Some(dsl::created_at.asc()), ) .await } } #[cfg(feature = "v2")] impl MerchantConnectorAccount { pub async fn update( self, conn: &PgPooledConn, merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.to_owned(), merchant_connector_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn delete_by_id( conn: &PgPooledConn, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::id.eq(id.to_owned())) .await } pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, ) -> StorageResult<Vec<Self>> { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } else { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::disabled.eq(false)), None, None, None, ) .await } } pub async fn list_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::profile_id.eq(profile_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } pub async fn list_enabled_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_type: common_enums::ConnectorType, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::disabled.eq(false)) .and(dsl::connector_type.eq(connector_type)), None, None, Some(dsl::created_at.asc()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/blocklist_lookup.rs
crates/diesel_models/src/query/blocklist_lookup.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}, schema::blocklist_lookup::dsl, PgPooledConn, StorageResult, }; impl BlocklistLookupNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup> { generics::generic_insert(conn, self).await } } impl BlocklistLookup { pub async fn find_by_merchant_id_fingerprint( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint.eq(fingerprint.to_owned())), ) .await } pub async fn delete_by_merchant_id_fingerprint( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint.eq(fingerprint.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/payment_method.rs
crates/diesel_models/src/query/payment_method.rs
use async_bb8_diesel::AsyncRunQueryDsl; #[cfg(feature = "v1")] use diesel::Table; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::ResultExt; use super::generics; #[cfg(feature = "v1")] 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, payment_method::{self, PaymentMethod, PaymentMethodNew}, PgPooledConn, StorageResult, }; impl PaymentMethodNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl PaymentMethod { pub async fn delete_by_payment_method_id( conn: &PgPooledConn, payment_method_id: String, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>( conn, dsl::payment_method_id.eq(payment_method_id), ) .await } pub async fn delete_by_merchant_id_payment_method_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_method_id: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_method_id.eq(payment_method_id.to_owned())), ) .await } pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::locker_id.eq(locker_id.to_owned()), ) .await } pub async fn find_by_payment_method_id( conn: &PgPooledConn, payment_method_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_method_id.eq(payment_method_id.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, None, ) .await } pub async fn find_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn find_by_merchant_id_payment_method_ids( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_method_ids: &[String], limit: Option<i64>, ) -> StorageResult<Vec<Self>> { if payment_method_ids.is_empty() { return Ok(Vec::new()); } generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_method_id.eq_any(payment_method_ids.to_owned())), limit, None, Some(dsl::payment_method_id.asc()), ) .await } pub async fn get_count_by_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> StorageResult<i64> { let filter = <Self as HasTable>::table() .count() .filter( dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(status.to_owned())), ) .into_boxed(); router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), generics::db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Failed to get a count of payment methods") } pub async fn get_count_by_merchant_id_status( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> StorageResult<i64> { let query = <Self as HasTable>::table().count().filter( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::status.eq(status.to_owned())), ); router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( query.get_result_async::<i64>(conn), generics::db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Failed to get a count of payment methods") } pub async fn find_by_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, status: storage_enums::PaymentMethodStatus, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(status)), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn update_with_payment_method_id( self, conn: &PgPooledConn, payment_method: payment_method::PaymentMethodUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::payment_method_id.eq(self.payment_method_id.to_owned()), payment_method, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } } #[cfg(feature = "v2")] impl PaymentMethod { pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalPaymentMethodId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned())) .await } pub async fn find_by_global_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, merchant_id: &common_utils::id_type::MerchantId, status: storage_enums::PaymentMethodStatus, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(status)), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn find_by_global_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id.eq(customer_id.to_owned()), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn update_with_id( self, conn: &PgPooledConn, payment_method: payment_method::PaymentMethodUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, pm_id.eq(self.id.to_owned()), payment_method) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_fingerprint_id( conn: &PgPooledConn, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::locker_fingerprint_id.eq(fingerprint_id.to_owned()), ) .await } pub async fn get_count_by_merchant_id_status( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> StorageResult<i64> { let query = <Self as HasTable>::table().count().filter( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::status.eq(status.to_owned())), ); router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( query.get_result_async::<i64>(conn), generics::db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Failed to get a count of payment methods") } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/payouts.rs
crates/diesel_models/src/query/payouts.rs
use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, JoinOnDsl, QueryDsl, }; use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums, errors, payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal}, query::generics::db_metrics, schema::{payout_attempt, payouts::dsl}, PgPooledConn, StorageResult, }; impl PayoutsNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Payouts> { generics::generic_insert(conn, self).await } } impl Payouts { pub async fn update( self, conn: &PgPooledConn, payout_update: PayoutsUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payout_id .eq(self.payout_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PayoutsUpdateInternal::from(payout_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(mut payouts) => payouts .pop() .ok_or(error_stack::report!(errors::DatabaseError::NotFound)), } } pub async fn find_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn update_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, payout: PayoutsUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), PayoutsUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn find_optional_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn get_total_count_of_payouts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<String>>, currency: Option<Vec<enums::Currency>>, status: Option<Vec<enums::PayoutStatus>>, payout_type: Option<Vec<enums::PayoutType>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .inner_join(payout_attempt::table.on(payout_attempt::dsl::payout_id.eq(dsl::payout_id))) .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::payout_id.eq_any(active_payout_ids.to_vec())) .into_boxed(); if let Some(connector) = connector { filter = filter.filter(payout_attempt::dsl::connector.eq_any(connector)); } if let Some(currency) = currency { filter = filter.filter(dsl::destination_currency.eq_any(currency)); } if let Some(status) = status { filter = filter.filter(dsl::status.eq_any(status)); } if let Some(payout_type) = payout_type { filter = filter.filter(dsl::payout_type.eq_any(payout_type)); } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering count of payouts") } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/unified_translations.rs
crates/diesel_models/src/query/unified_translations.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use crate::{ errors, query::generics, schema::unified_translations::dsl, unified_translations::{UnifiedTranslationsUpdateInternal, *}, PgPooledConn, StorageResult, }; impl UnifiedTranslationsNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UnifiedTranslations> { generics::generic_insert(conn, self).await } } impl UnifiedTranslations { pub async fn find_by_unified_code_unified_message_locale( conn: &PgPooledConn, unified_code: String, unified_message: String, locale: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::unified_code .eq(unified_code) .and(dsl::unified_message.eq(unified_message)) .and(dsl::locale.eq(locale)), ) .await } pub async fn update_by_unified_code_unified_message_locale( conn: &PgPooledConn, unified_code: String, unified_message: String, locale: String, data: UnifiedTranslationsUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, UnifiedTranslationsUpdateInternal, _, _, >( conn, dsl::unified_code .eq(unified_code) .and(dsl::unified_message.eq(unified_message)) .and(dsl::locale.eq(locale)), data.into(), ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating unified_translations entry") }) } pub async fn delete_by_unified_code_unified_message_locale( conn: &PgPooledConn, unified_code: String, unified_message: String, locale: String, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::unified_code .eq(unified_code) .and(dsl::unified_message.eq(unified_message)) .and(dsl::locale.eq(locale)), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/utils.rs
crates/diesel_models/src/query/utils.rs
use crate::{schema, schema_v2}; /// This trait will return a single column as primary key even in case of composite primary key. /// /// In case of composite key, it will return the column that is used as local unique. pub(super) trait GetPrimaryKey: diesel::Table { type PK: diesel::ExpressionMethods; fn get_primary_key(&self) -> Self::PK; } /// This trait must be implemented for all composite keys. pub(super) trait CompositeKey { type UK; /// It will return the local unique key of the composite key. /// /// If `(attempt_id, merchant_id)` is the composite key for `payment_attempt` table, then it will return `attempt_id`. fn get_local_unique_key(&self) -> Self::UK; } /// implementation of `CompositeKey` trait for all the composite keys must be done here. mod composite_key { use super::{schema, schema_v2, CompositeKey}; impl CompositeKey for <schema::payment_attempt::table as diesel::Table>::PrimaryKey { type UK = schema::payment_attempt::dsl::attempt_id; fn get_local_unique_key(&self) -> Self::UK { self.0 } } impl CompositeKey for <schema::refund::table as diesel::Table>::PrimaryKey { type UK = schema::refund::dsl::refund_id; fn get_local_unique_key(&self) -> Self::UK { self.1 } } impl CompositeKey for <schema::customers::table as diesel::Table>::PrimaryKey { type UK = schema::customers::dsl::customer_id; fn get_local_unique_key(&self) -> Self::UK { self.0 } } impl CompositeKey for <schema::blocklist::table as diesel::Table>::PrimaryKey { type UK = schema::blocklist::dsl::fingerprint_id; fn get_local_unique_key(&self) -> Self::UK { self.1 } } impl CompositeKey for <schema::incremental_authorization::table as diesel::Table>::PrimaryKey { type UK = schema::incremental_authorization::dsl::authorization_id; fn get_local_unique_key(&self) -> Self::UK { self.0 } } impl CompositeKey for <schema::hyperswitch_ai_interaction::table as diesel::Table>::PrimaryKey { type UK = schema::hyperswitch_ai_interaction::dsl::id; fn get_local_unique_key(&self) -> Self::UK { self.0 } } impl CompositeKey for <schema_v2::incremental_authorization::table as diesel::Table>::PrimaryKey { type UK = schema_v2::incremental_authorization::dsl::authorization_id; fn get_local_unique_key(&self) -> Self::UK { self.0 } } impl CompositeKey for <schema_v2::blocklist::table as diesel::Table>::PrimaryKey { type UK = schema_v2::blocklist::dsl::fingerprint_id; fn get_local_unique_key(&self) -> Self::UK { self.1 } } } /// This macro will implement the `GetPrimaryKey` trait for all the tables with single primary key. macro_rules! impl_get_primary_key { ($($table:ty),*) => { $( impl GetPrimaryKey for $table { type PK = <$table as diesel::Table>::PrimaryKey; fn get_primary_key(&self) -> Self::PK { <Self as diesel::Table>::primary_key(self) } } )* }; } impl_get_primary_key!( // v1 tables schema::dashboard_metadata::table, schema::merchant_connector_account::table, schema::merchant_key_store::table, schema::payment_methods::table, schema::user_authentication_methods::table, schema::user_key_store::table, schema::users::table, schema::api_keys::table, schema::captures::table, schema::business_profile::table, schema::mandate::dsl::mandate, schema::dispute::table, schema::events::table, schema::merchant_account::table, schema::process_tracker::table, schema::invoice::table, schema::subscription::table, // v2 tables schema_v2::dashboard_metadata::table, schema_v2::merchant_connector_account::table, schema_v2::merchant_key_store::table, schema_v2::payment_methods::table, schema_v2::user_authentication_methods::table, schema_v2::user_key_store::table, schema_v2::users::table, schema_v2::api_keys::table, schema_v2::captures::table, schema_v2::business_profile::table, schema_v2::mandate::table, schema_v2::dispute::table, schema_v2::events::table, schema_v2::merchant_account::table, schema_v2::process_tracker::table, schema_v2::refund::table, schema_v2::customers::table, schema_v2::payment_attempt::table ); /// This macro will implement the `GetPrimaryKey` trait for all the tables with composite key. macro_rules! impl_get_primary_key_for_composite { ($($table:ty),*) => { $( impl GetPrimaryKey for $table { type PK = <<$table as diesel::Table>::PrimaryKey as CompositeKey>::UK; fn get_primary_key(&self) -> Self::PK { <Self as diesel::Table>::primary_key(self).get_local_unique_key() } } )* }; } impl_get_primary_key_for_composite!( schema::payment_attempt::table, schema::refund::table, schema::customers::table, schema::blocklist::table, schema::incremental_authorization::table, schema::hyperswitch_ai_interaction::table, schema_v2::incremental_authorization::table, schema_v2::blocklist::table );
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/gsm.rs
crates/diesel_models/src/query/gsm.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use crate::{ errors, gsm::*, query::generics, schema::gateway_status_map::dsl, PgPooledConn, StorageResult, }; impl GatewayStatusMappingNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GatewayStatusMap> { generics::generic_insert(conn, self).await } } impl GatewayStatusMap { pub async fn find( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await } pub async fn retrieve_decision( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<String> { Self::find(conn, connector, flow, sub_flow, code, message) .await .map(|item| item.decision) } pub async fn update( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, gsm: GatewayStatusMappingUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, GatewayStatusMapperUpdateInternal, _, _, >( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), gsm.into(), ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating gsm entry") }) } pub async fn delete( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/authentication.rs
crates/diesel_models/src/query/authentication.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ authentication::{ Authentication, AuthenticationNew, AuthenticationUpdate, AuthenticationUpdateInternal, }, errors, schema::authentication::dsl, PgPooledConn, StorageResult, }; impl AuthenticationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> { generics::generic_insert(conn, self).await } } impl Authentication { pub async fn update_by_merchant_id_authentication_id( conn: &PgPooledConn, merchant_id: common_utils::id_type::MerchantId, authentication_id: common_utils::id_type::AuthenticationId, authorization_update: AuthenticationUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authentication_id.eq(authentication_id.to_owned())), AuthenticationUpdateInternal::from(authorization_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => Err(error.attach_printable( "Authentication with the given Authentication ID does not exist", )), errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authentication_id.eq(authentication_id.to_owned())), ) .await } _ => Err(error), }, result => result, } } pub async fn find_by_merchant_id_authentication_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, authentication_id: &common_utils::id_type::AuthenticationId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authentication_id.eq(authentication_id.to_owned())), ) .await } pub async fn find_authentication_by_merchant_id_connector_authentication_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_authentication_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_authentication_id.eq(connector_authentication_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/business_profile.rs
crates/diesel_models/src/query/business_profile.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::business_profile::dsl::{self, profile_id as dsl_identifier}; #[cfg(feature = "v2")] use crate::schema_v2::business_profile::dsl::{self, id as dsl_identifier}; use crate::{ business_profile::{Profile, ProfileNew, ProfileUpdateInternal}, errors, PgPooledConn, StorageResult, }; impl ProfileNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Profile> { generics::generic_insert(conn, self).await } } impl Profile { pub async fn update_by_profile_id( self, conn: &PgPooledConn, business_profile: ProfileUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), business_profile, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl_identifier.eq(profile_id.to_owned()), ) .await } pub async fn find_by_merchant_id_profile_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl_identifier.eq(profile_id.to_owned())), ) .await } pub async fn find_by_profile_name_merchant_id( conn: &PgPooledConn, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_name .eq(profile_name.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } pub async fn list_profile_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, None, ) .await } pub async fn delete_by_profile_id_merchant_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl_identifier .eq(profile_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/mandate.rs
crates/diesel_models/src/query/mandate.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use error_stack::report; use super::generics; use crate::{errors, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult}; impl MandateNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> { generics::generic_insert(conn, self).await } } impl Mandate { pub async fn find_by_merchant_id_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::mandate_id.eq(mandate_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_mandate_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_mandate_id.eq(connector_mandate_id.to_owned())), ) .await } pub async fn find_by_merchant_id_customer_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, customer_id: &common_utils::id_type::CustomerId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::customer_id.eq(customer_id.to_owned())), None, None, None, ) .await } //Fix this function once V2 mandate is schema is being built #[cfg(feature = "v2")] pub async fn find_by_global_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::customer_id.eq(customer_id.to_owned()), None, None, None, ) .await } pub async fn update_by_merchant_id_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_id: &str, mandate: MandateUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::mandate_id.eq(mandate_id.to_owned())), mandate, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating mandate") }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/role.rs
crates/diesel_models/src/query/role.rs
use async_bb8_diesel::AsyncRunQueryDsl; use common_enums::EntityType; use common_utils::id_type; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use strum::IntoEnumIterator; use crate::{ enums::RoleScope, errors, query::generics, role::*, schema::roles::dsl, PgPooledConn, StorageResult, }; impl RoleNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Role> { generics::generic_insert(conn, self).await } } impl Role { fn get_entity_list( current_entity: EntityType, is_lineage_data_required: bool, ) -> Vec<EntityType> { is_lineage_data_required .then(|| { EntityType::iter() .filter(|variant| *variant <= current_entity) .collect() }) .unwrap_or(vec![current_entity]) } pub async fn find_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id.eq(role_id.to_owned()), ) .await } pub async fn find_by_role_id_in_lineage( conn: &PgPooledConn, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())) .and( dsl::scope .eq(RoleScope::Organization) .or(dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::scope.eq(RoleScope::Merchant))) .or(dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::scope.eq(RoleScope::Profile))), ), ) .await } pub async fn find_by_role_id_org_id_tenant_id( conn: &PgPooledConn, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())), ) .await } pub async fn update_by_role_id( conn: &PgPooledConn, role_id: &str, role_update: RoleUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::role_id.eq(role_id.to_owned()), RoleUpdateInternal::from(role_update), ) .await } pub async fn delete_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id.eq(role_id.to_owned()), ) .await } //TODO: Remove once generic_list_roles_by_entity_type is stable pub async fn generic_roles_list_for_org( conn: &PgPooledConn, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::tenant_id.eq(tenant_id).and(dsl::org_id.eq(org_id))) .into_boxed(); if let Some(merchant_id) = merchant_id { query = query.filter( (dsl::merchant_id .eq(merchant_id) .and(dsl::scope.eq(RoleScope::Merchant))) .or(dsl::scope.eq(RoleScope::Organization)), ); } if let Some(entity_type) = entity_type { query = query.filter(dsl::entity_type.eq(entity_type)) } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } pub async fn generic_list_roles_by_entity_type( conn: &PgPooledConn, payload: ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .into_boxed() .filter(dsl::tenant_id.eq(tenant_id)) .filter(dsl::org_id.eq(org_id)); match payload { ListRolesByEntityPayload::Organization => { let entity_in_vec = Self::get_entity_list(EntityType::Organization, is_lineage_data_required); query = query.filter(dsl::entity_type.eq_any(entity_in_vec)) } ListRolesByEntityPayload::Merchant(merchant_id) => { let entity_in_vec = Self::get_entity_list(EntityType::Merchant, is_lineage_data_required); query = query .filter( dsl::scope .eq(RoleScope::Organization) .or(dsl::merchant_id.eq(merchant_id)), ) .filter(dsl::entity_type.eq_any(entity_in_vec)) } ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = Self::get_entity_list(EntityType::Profile, is_lineage_data_required); query = query .filter( dsl::scope .eq(RoleScope::Organization) .or(dsl::scope .eq(RoleScope::Merchant) .and(dsl::merchant_id.eq(merchant_id.clone()))) .or(dsl::profile_id.eq(profile_id)), ) .filter(dsl::entity_type.eq_any(entity_in_vec)) } }; router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => Err(report!(err)).change_context(errors::DatabaseError::Others), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/events.rs
crates/diesel_models/src/query/events.rs
use std::collections::HashSet; use diesel::{ associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, }; use error_stack::ResultExt; use super::generics; use crate::{ errors::DatabaseError, events::{Event, EventNew, EventUpdateInternal}, schema::events::dsl, PgPooledConn, StorageResult, }; impl EventNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> { generics::generic_insert(conn, self).await } } impl Event { pub async fn find_by_merchant_id_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(event_id.to_owned())), ) .await } pub async fn find_by_merchant_id_idempotent_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())), ) .await } pub async fn list_initial_attempts_by_merchant_id_primary_object_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::primary_object_id.eq(primary_object_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn find_initial_attempt_by_merchant_id_initial_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, ) -> StorageResult<Option<Self>> { let predicate = dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(initial_attempt_id.to_owned())); let result = generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await; match result { Ok(event) => Ok(Some(event)), Err(err) => match err.current_context() { DatabaseError::NotFound => Ok(None), _ => Err(err).attach_printable("Error finding event by initial_attempt_id"), }, } } #[allow(clippy::too_many_arguments)] pub async fn list_initial_attempts_by_merchant_id_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> StorageResult<Vec<Self>> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .order(dsl::created_at.desc()) .into_boxed(); query = Self::apply_filters( query, None, (dsl::created_at, created_after, created_before), limit, offset, event_types, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found .attach_printable("Error filtering events by constraints") } pub async fn list_by_merchant_id_initial_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn list_initial_attempts_by_profile_id_primary_object_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::business_profile_id.eq(profile_id.to_owned())) .and(dsl::primary_object_id.eq(primary_object_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn find_initial_attempt_by_profile_id_initial_attempt_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, initial_attempt_id: &str, ) -> StorageResult<Option<Self>> { let predicate = dsl::business_profile_id .eq(profile_id.to_owned()) .and(dsl::event_id.eq(initial_attempt_id.to_owned())); let result = generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await; match result { Ok(event) => Ok(Some(event)), Err(err) => match err.current_context() { DatabaseError::NotFound => Ok(None), _ => Err(err).attach_printable("Error finding event by initial_attempt_id"), }, } } #[allow(clippy::too_many_arguments)] pub async fn list_initial_attempts_by_profile_id_constraints( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> StorageResult<Vec<Self>> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::business_profile_id.eq(profile_id.to_owned())), ) .order(dsl::created_at.desc()) .into_boxed(); query = Self::apply_filters( query, None, (dsl::created_at, created_after, created_before), limit, offset, event_types, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found .attach_printable("Error filtering events by constraints") } pub async fn list_by_profile_id_initial_attempt_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, initial_attempt_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::business_profile_id .eq(profile_id.to_owned()) .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn update_by_merchant_id_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: EventUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(event_id.to_owned())), event, ) .await } fn apply_filters<T>( mut query: T, profile_id: Option<common_utils::id_type::ProfileId>, (column, created_after, created_before): ( dsl::created_at, time::PrimitiveDateTime, time::PrimitiveDateTime, ), limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> T where T: diesel::query_dsl::methods::LimitDsl<Output = T> + diesel::query_dsl::methods::OffsetDsl<Output = T>, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::GtEq<dsl::created_at, time::PrimitiveDateTime>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::LtEq<dsl::created_at, time::PrimitiveDateTime>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::Eq<dsl::business_profile_id, common_utils::id_type::ProfileId>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::EqAny<dsl::event_type, HashSet<common_enums::EventType>>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>, Output = T, >, { if let Some(profile_id) = profile_id { query = query.filter(dsl::business_profile_id.eq(profile_id)); } query = query .filter(column.ge(created_after)) .filter(column.le(created_before)); if let Some(limit) = limit { query = query.limit(limit); } if let Some(offset) = offset { query = query.offset(offset); } if !event_types.is_empty() { query = query.filter(dsl::event_type.eq_any(event_types)); } if let Some(is_delivered) = is_delivered { query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered)); } query } pub async fn count_initial_attempts_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> StorageResult<i64> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .count() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .into_boxed(); query = Self::apply_filters( query, profile_id, (dsl::created_at, created_after, created_before), None, None, event_types, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>( query.get_result_async::<i64>(conn), DatabaseOperation::Count, ) .await .change_context(DatabaseError::Others) .attach_printable("Error counting events by constraints") } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/authorization.rs
crates/diesel_models/src/query/authorization.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ authorization::{ Authorization, AuthorizationNew, AuthorizationUpdate, AuthorizationUpdateInternal, }, errors, schema::incremental_authorization::dsl, PgPooledConn, StorageResult, }; impl AuthorizationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authorization> { generics::generic_insert(conn, self).await } } impl Authorization { pub async fn update_by_merchant_id_authorization_id( conn: &PgPooledConn, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization_update: AuthorizationUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authorization_id.eq(authorization_id.to_owned())), AuthorizationUpdateInternal::from(authorization_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => Err(error.attach_printable( "Authorization with the given Authorization ID does not exist", )), errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authorization_id.eq(authorization_id.to_owned())), ) .await } _ => Err(error), }, result => result, } } pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, Some(dsl::created_at.asc()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/dashboard_metadata.rs
crates/diesel_models/src/query/dashboard_metadata.rs
use common_utils::id_type; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use crate::{ enums, query::generics, schema::dashboard_metadata::dsl, user::dashboard_metadata::{ DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate, DashboardMetadataUpdateInternal, }, PgPooledConn, StorageResult, }; impl DashboardMetadataNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DashboardMetadata> { generics::generic_insert(conn, self).await } } impl DashboardMetadata { pub async fn update( conn: &PgPooledConn, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: DashboardMetadataUpdate, ) -> StorageResult<Self> { let predicate = dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::org_id.eq(org_id.to_owned())) .and(dsl::data_key.eq(data_key.to_owned())); if let Some(uid) = user_id { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, predicate.and(dsl::user_id.eq(uid)), DashboardMetadataUpdateInternal::from(dashboard_metadata_update), ) .await } else { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, predicate.and(dsl::user_id.is_null()), DashboardMetadataUpdateInternal::from(dashboard_metadata_update), ) .await } } pub async fn find_user_scoped_dashboard_metadata( conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_types: Vec<enums::DashboardMetadata>, ) -> StorageResult<Vec<Self>> { let predicate = dsl::user_id .eq(user_id) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::org_id.eq(org_id)) .and(dsl::data_key.eq_any(data_types)); generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, predicate, None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn find_merchant_scoped_dashboard_metadata( conn: &PgPooledConn, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_types: Vec<enums::DashboardMetadata>, ) -> StorageResult<Vec<Self>> { let predicate = dsl::merchant_id .eq(merchant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::data_key.eq_any(data_types)); generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, predicate, None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::user_id .eq(user_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id .eq(user_id) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::data_key.eq(data_key)), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/refund.rs
crates/diesel_models/src/query/refund.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::refund::dsl; #[cfg(feature = "v2")] use crate::schema_v2::refund::dsl; use crate::{ errors, refund::{Refund, RefundNew, RefundUpdate, RefundUpdateInternal}, PgPooledConn, StorageResult, }; impl RefundNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Refund> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl Refund { pub async fn update(self, conn: &PgPooledConn, refund: RefundUpdate) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::refund_id .eq(self.refund_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), RefundUpdateInternal::from(refund), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } // This is required to be changed for KV. pub async fn find_by_merchant_id_refund_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::refund_id.eq(refund_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_refund_id_connector( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_refund_id.eq(connector_refund_id.to_owned())) .and(dsl::connector.eq(connector.to_owned())), ) .await } pub async fn find_by_internal_reference_id_merchant_id( conn: &PgPooledConn, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::internal_reference_id.eq(internal_reference_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_transaction_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), None, None, None, ) .await } pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } } #[cfg(feature = "v2")] impl Refund { pub async fn update_with_id( self, conn: &PgPooledConn, refund: RefundUpdate, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.to_owned(), RefundUpdateInternal::from(refund), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_global_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalRefundId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } pub async fn find_by_merchant_id_connector_transaction_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), None, None, None, ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/routing_algorithm.rs
crates/diesel_models/src/query/routing_algorithm.rs
use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; use error_stack::{report, ResultExt}; use time::PrimitiveDateTime; use crate::{ enums, errors::DatabaseError, query::generics, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, schema::routing_algorithm::dsl, PgPooledConn, StorageResult, }; impl RoutingAlgorithm { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_algorithm_id_merchant_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } pub async fn find_by_algorithm_id_profile_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), ) .await } pub async fn find_metadata_by_algorithm_id_profile_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<RoutingProfileMetadata> { Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter( dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), ) .limit(1) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .next() .ok_or(report!(DatabaseError::NotFound)) .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) } pub async fn list_metadata_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::algorithm_id, dsl::profile_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::profile_id.eq(profile_id.to_owned())) .limit(limit) .offset(offset) .load_async::<( common_utils::id_type::RoutingId, common_utils::id_type::ProfileId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( algorithm_id, profile_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, profile_id, } }, ) .collect()) } pub async fn list_metadata_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .limit(limit) .offset(offset) .order(dsl::modified_at.desc()) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) .collect()) } pub async fn list_metadata_by_merchant_id_transaction_type( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::algorithm_for.eq(transaction_type.to_owned())) .limit(limit) .offset(offset) .order(dsl::modified_at.desc()) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) .collect()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/connector_response.rs
crates/diesel_models/src/query/connector_response.rs
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use router_env::{instrument, logger, tracing}; use super::generics; use crate::{ connector_response::{ ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate, ConnectorResponseUpdateInternal, }, errors, payment_attempt::{PaymentAttempt, PaymentAttemptUpdate, PaymentAttemptUpdateInternal}, schema::{connector_response::dsl, payment_attempt::dsl as pa_dsl}, PgPooledConn, StorageResult, }; impl ConnectorResponseNew { #[instrument(skip(conn))] pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ConnectorResponse> { let payment_attempt_update = PaymentAttemptUpdate::ConnectorResponse { authentication_data: self.authentication_data.clone(), encoded_data: self.encoded_data.clone(), connector_transaction_id: self.connector_transaction_id.clone(), connector: self.connector_name.clone(), updated_by: self.updated_by.clone(), charge_id: self.charge_id.clone(), }; let _payment_attempt: Result<PaymentAttempt, _> = generics::generic_update_with_unique_predicate_get_result::< <PaymentAttempt as HasTable>::Table, _, _, _, >( conn, pa_dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt_update), ) .await .inspect_err(|err| { logger::error!( "Error while updating payment attempt in connector_response flow {:?}", err ); }); generics::generic_insert(conn, self).await } } impl ConnectorResponse { #[instrument(skip(conn))] pub async fn update( self, conn: &PgPooledConn, connector_response: ConnectorResponseUpdate, ) -> StorageResult<Self> { let payment_attempt_update = match connector_response.clone() { ConnectorResponseUpdate::ResponseUpdate { connector_transaction_id, authentication_data, encoded_data, connector_name, charge_id, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector: connector_name, charge_id, updated_by, }, ConnectorResponseUpdate::ErrorUpdate { connector_name, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data: None, encoded_data: None, connector_transaction_id: None, connector: connector_name, charge_id: None, updated_by, }, }; let _payment_attempt: Result<PaymentAttempt, _> = generics::generic_update_with_unique_predicate_get_result::< <PaymentAttempt as HasTable>::Table, _, _, _, >( conn, pa_dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt_update), ) .await .inspect_err(|err| { logger::error!( "Error while updating payment attempt in connector_response flow {:?}", err ); }); let connector_response_result = match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(self.merchant_id.clone()) .and(dsl::payment_id.eq(self.payment_id.clone())) .and(dsl::attempt_id.eq(self.attempt_id.clone())), ConnectorResponseUpdateInternal::from(connector_response), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, }; connector_response_result } #[instrument(skip(conn))] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { let connector_response: Self = generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()).and( dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await?; match generics::generic_find_one::<<PaymentAttempt as HasTable>::Table, _, _>( conn, pa_dsl::payment_id.eq(payment_id.to_owned()).and( pa_dsl::merchant_id .eq(merchant_id.to_owned()) .and(pa_dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await { Ok::<PaymentAttempt, _>(payment_attempt) => { if payment_attempt.authentication_data != connector_response.authentication_data { logger::error!( "Not Equal pa_authentication_data : {:?}, cr_authentication_data: {:?} ", payment_attempt.authentication_data, connector_response.authentication_data ); } if payment_attempt.encoded_data != connector_response.encoded_data { logger::error!( "Not Equal pa_encoded_data : {:?}, cr_encoded_data: {:?} ", payment_attempt.encoded_data, connector_response.encoded_data ); } if payment_attempt.connector_transaction_id != connector_response.connector_transaction_id { logger::error!( "Not Equal pa_connector_transaction_id : {:?}, cr_connector_transaction_id: {:?} ", payment_attempt.connector_transaction_id, connector_response.connector_transaction_id ); } if payment_attempt.connector != connector_response.connector_name { logger::error!( "Not Equal pa_connector : {:?}, cr_connector_name: {:?} ", payment_attempt.connector, connector_response.connector_name ); } } Err(err) => { logger::error!( "Error while finding payment attempt in connector_response flow {:?}", err ); } } Ok(connector_response) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/configs.rs
crates/diesel_models/src/query/configs.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal}, errors, schema::configs::dsl, PgPooledConn, StorageResult, }; impl ConfigNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Config> { generics::generic_insert(conn, self).await } } impl Config { pub async fn find_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, key.to_owned()).await } pub async fn update_by_key( conn: &PgPooledConn, key: &str, config_update: ConfigUpdate, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, key.to_owned(), ConfigUpdateInternal::from(config_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, key.to_owned(), ) .await } _ => Err(error), }, result => result, } } pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::key.eq(key.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
use diesel::{associations::HasTable, ExpressionMethods}; use crate::{ hyperswitch_ai_interaction::{HyperswitchAiInteraction, HyperswitchAiInteractionNew}, query::generics, schema::hyperswitch_ai_interaction::dsl, PgPooledConn, StorageResult, }; impl HyperswitchAiInteractionNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<HyperswitchAiInteraction> { generics::generic_insert(conn, self).await } } impl HyperswitchAiInteraction { pub async fn filter_by_optional_merchant_id( conn: &PgPooledConn, merchant_id: Option<&common_utils::id_type::MerchantId>, limit: i64, offset: i64, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.cloned()), Some(limit), Some(offset), Some(dsl::created_at.desc()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/reverse_lookup.rs
crates/diesel_models/src/query/reverse_lookup.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ reverse_lookup::{ReverseLookup, ReverseLookupNew}, schema::reverse_lookup::dsl, PgPooledConn, StorageResult, }; impl ReverseLookupNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ReverseLookup> { generics::generic_insert(conn, self).await } pub async fn batch_insert( reverse_lookups: Vec<Self>, conn: &PgPooledConn, ) -> StorageResult<()> { generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?; Ok(()) } } impl ReverseLookup { pub async fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::lookup_id.eq(lookup_id.to_owned()), ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/merchant_key_store.rs
crates/diesel_models/src/query/merchant_key_store.rs
use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ merchant_key_store::{MerchantKeyStore, MerchantKeyStoreNew}, schema::merchant_key_store::dsl, PgPooledConn, StorageResult, }; impl MerchantKeyStoreNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantKeyStore> { generics::generic_insert(conn, self).await } } impl MerchantKeyStore { pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } pub async fn list_multiple_key_stores( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq_any(merchant_ids), None, None, None, ) .await } pub async fn list_all_key_stores( conn: &PgPooledConn, from: u32, limit: u32, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::merchant_id.ne_all(vec!["".to_string()]), Some(limit.into()), Some(from.into()), None, ) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/tokenization.rs
crates/diesel_models/src/query/tokenization.rs
#[cfg(feature = "v2")] use diesel::associations::HasTable; #[cfg(feature = "v2")] use diesel::ExpressionMethods; #[cfg(feature = "v2")] use crate::{ errors, query::generics, schema_v2::tokenization, tokenization as tokenization_diesel, PgPooledConn, StorageResult, }; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl tokenization_diesel::Tokenization { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalTokenId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, tokenization::dsl::id.eq(id.to_owned()), ) .await } pub async fn update_with_id( self, conn: &PgPooledConn, tokenization_record: tokenization_diesel::TokenizationUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, tokenization::dsl::id.eq(self.id.to_owned()), tokenization_record, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/user/theme.rs
crates/diesel_models/src/query/user/theme.rs
use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::types::user::ThemeLineage; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use router_env::logger; use crate::{ errors::DatabaseError, query::generics::{ self, db_metrics::{track_database_call, DatabaseOperation}, }, schema::themes::dsl, user::theme::{Theme, ThemeNew, ThemeUpdate, ThemeUpdateInternal}, PgPooledConn, StorageResult, }; impl ThemeNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> { generics::generic_insert(conn, self).await } } impl Theme { fn lineage_filter( lineage: ThemeLineage, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { match lineage { ThemeLineage::Tenant { tenant_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .nullable(), ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ), ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.is_null()), ), ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ), } } /// Matches all themes that belong to the specified hierarchy level or below fn lineage_hierarchy_filter( lineage: ThemeLineage, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { match lineage { ThemeLineage::Tenant { tenant_id } => Box::new(dsl::tenant_id.eq(tenant_id).nullable()), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .nullable(), ), ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .nullable(), ), ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)) .nullable(), ), } } pub async fn find_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id.eq(theme_id), ) .await } pub async fn find_most_specific_theme_in_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { let query = <Self as HasTable>::table().into_boxed(); let query = lineage .get_same_and_higher_lineages() .into_iter() .fold(query, |mut query, lineage| { query = query.or_filter(Self::lineage_filter(lineage)); query }); logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); let data: Vec<Self> = match track_database_call::<Self, _, _>( query.get_results_async(conn), DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), _ => Err(report!(err)).change_context(DatabaseError::Others), }, }?; data.into_iter() .min_by_key(|theme| theme.entity_type) .ok_or(report!(DatabaseError::NotFound)) } pub async fn find_by_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, Self::lineage_filter(lineage), ) .await } pub async fn update_by_theme_id( conn: &PgPooledConn, theme_id: String, update: ThemeUpdate, ) -> StorageResult<Self> { let update_internal: ThemeUpdateInternal = update.into(); let predicate = dsl::theme_id.eq(theme_id); generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, predicate, update_internal) .await } pub async fn delete_by_theme_id_and_lineage( conn: &PgPooledConn, theme_id: String, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id .eq(theme_id) .and(Self::lineage_filter(lineage)), ) .await } pub async fn delete_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id.eq(theme_id), ) .await } /// Finds all themes that match the specified lineage hierarchy. pub async fn find_all_by_lineage_hierarchy( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Vec<Self>> { let filter = Self::lineage_hierarchy_filter(lineage); let query = <Self as HasTable>::table().filter(filter).into_boxed(); logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match track_database_call::<Self, _, _>( query.get_results_async(conn), DatabaseOperation::Filter, ) .await { Ok(themes) => Ok(themes), Err(err) => match err { DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), _ => Err(report!(err)).change_context(DatabaseError::Others), }, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/query/user/sample_data.rs
crates/diesel_models/src/query/user/sample_data.rs
use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{associations::HasTable, debug_query, ExpressionMethods, TextExpressionMethods}; use error_stack::ResultExt; use router_env::logger; #[cfg(feature = "v1")] use crate::schema::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, refund::dsl as refund_dsl, }; #[cfg(feature = "v2")] use crate::schema_v2::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, refund::dsl as refund_dsl, }; use crate::{ errors, schema::dispute::dsl as dispute_dsl, Dispute, DisputeNew, PaymentAttempt, PaymentIntent, PgPooledConn, Refund, RefundNew, StorageResult, }; #[cfg(feature = "v1")] use crate::{user, PaymentIntentNew}; #[cfg(feature = "v1")] pub async fn insert_payment_intents( conn: &PgPooledConn, batch: Vec<PaymentIntentNew>, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::insert_into(<PaymentIntent>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting payment intents") } #[cfg(feature = "v1")] pub async fn insert_payment_attempts( conn: &PgPooledConn, batch: Vec<user::sample_data::PaymentAttemptBatchNew>, ) -> StorageResult<Vec<PaymentAttempt>> { let query = diesel::insert_into(<PaymentAttempt>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting payment attempts") } pub async fn insert_refunds( conn: &PgPooledConn, batch: Vec<RefundNew>, ) -> StorageResult<Vec<Refund>> { let query = diesel::insert_into(<Refund>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting refunds") } pub async fn insert_disputes( conn: &PgPooledConn, batch: Vec<DisputeNew>, ) -> StorageResult<Vec<Dispute>> { let query = diesel::insert_into(<Dispute>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting disputes") } #[cfg(feature = "v1")] pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::delete(<PaymentIntent>::table()) .filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_intent_dsl::payment_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment intents") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } #[cfg(feature = "v2")] pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::delete(<PaymentIntent>::table()) .filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_intent_dsl::merchant_reference_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment intents") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } pub async fn delete_payment_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentAttempt>> { let query = diesel::delete(<PaymentAttempt>::table()) .filter(payment_attempt_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_attempt_dsl::payment_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment attempts") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } pub async fn delete_refunds( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Refund>> { let query = diesel::delete(<Refund>::table()) .filter(refund_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(refund_dsl::payment_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting refunds") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } pub async fn delete_disputes( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Dispute>> { let query = diesel::delete(<Dispute>::table()) .filter(dispute_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dispute_dsl::dispute_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting disputes") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user/theme.rs
crates/diesel_models/src/user/theme.rs
use common_enums::EntityType; use common_utils::{ date_time, id_type, types::user::{EmailThemeConfig, ThemeLineage}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use router_derive::DebugAsDisplay; use time::PrimitiveDateTime; use crate::schema::themes; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))] pub struct Theme { pub theme_id: String, pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, pub email_primary_color: String, pub email_foreground_color: String, pub email_background_color: String, pub email_entity_name: String, pub email_entity_logo_url: String, } #[derive(Clone, Debug, Insertable, DebugAsDisplay)] #[diesel(table_name = themes)] pub struct ThemeNew { pub theme_id: String, pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, pub email_primary_color: String, pub email_foreground_color: String, pub email_background_color: String, pub email_entity_name: String, pub email_entity_logo_url: String, } impl ThemeNew { pub fn new( theme_id: String, theme_name: String, lineage: ThemeLineage, email_config: EmailThemeConfig, ) -> Self { let now = date_time::now(); Self { theme_id, theme_name, tenant_id: lineage.tenant_id().to_owned(), org_id: lineage.org_id().cloned(), merchant_id: lineage.merchant_id().cloned(), profile_id: lineage.profile_id().cloned(), entity_type: lineage.entity_type(), created_at: now, last_modified_at: now, email_primary_color: email_config.primary_color, email_foreground_color: email_config.foreground_color, email_background_color: email_config.background_color, email_entity_name: email_config.entity_name, email_entity_logo_url: email_config.entity_logo_url, } } } impl Theme { pub fn email_config(&self) -> EmailThemeConfig { EmailThemeConfig { primary_color: self.email_primary_color.clone(), foreground_color: self.email_foreground_color.clone(), background_color: self.email_background_color.clone(), entity_name: self.email_entity_name.clone(), entity_logo_url: self.email_entity_logo_url.clone(), } } } #[derive(Clone, Debug, Default, AsChangeset, DebugAsDisplay)] #[diesel(table_name = themes)] pub struct ThemeUpdateInternal { pub email_primary_color: Option<String>, pub email_foreground_color: Option<String>, pub email_background_color: Option<String>, pub email_entity_name: Option<String>, pub email_entity_logo_url: Option<String>, } #[derive(Clone)] pub enum ThemeUpdate { EmailConfig { email_config: EmailThemeConfig }, } impl From<ThemeUpdate> for ThemeUpdateInternal { fn from(value: ThemeUpdate) -> Self { match value { ThemeUpdate::EmailConfig { email_config } => Self { email_primary_color: Some(email_config.primary_color), email_foreground_color: Some(email_config.foreground_color), email_background_color: Some(email_config.background_color), email_entity_name: Some(email_config.entity_name), email_entity_logo_url: Some(email_config.entity_logo_url), }, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user/sample_data.rs
crates/diesel_models/src/user/sample_data.rs
#[cfg(feature = "v1")] use common_enums::{ AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod, PaymentMethodType, }; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; #[cfg(feature = "v1")] use common_utils::types::{ConnectorTransactionId, MinorUnit}; #[cfg(feature = "v1")] use serde::{Deserialize, Serialize}; #[cfg(feature = "v1")] use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::{ enums::{MandateDataType, MandateDetails}, schema::payment_attempt, ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptNew, }; // #[cfg(feature = "v2")] // #[derive( // Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, // )] // #[diesel(table_name = payment_attempt)] // pub struct PaymentAttemptBatchNew { // pub payment_id: common_utils::id_type::PaymentId, // pub merchant_id: common_utils::id_type::MerchantId, // pub status: AttemptStatus, // pub error_message: Option<String>, // pub surcharge_amount: Option<i64>, // pub tax_on_surcharge: Option<i64>, // pub payment_method_id: Option<String>, // pub authentication_type: Option<AuthenticationType>, // #[serde(with = "common_utils::custom_serde::iso8601")] // pub created_at: PrimitiveDateTime, // #[serde(with = "common_utils::custom_serde::iso8601")] // pub modified_at: PrimitiveDateTime, // #[serde(default, with = "common_utils::custom_serde::iso8601::option")] // pub last_synced: Option<PrimitiveDateTime>, // pub cancellation_reason: Option<String>, // pub browser_info: Option<serde_json::Value>, // pub payment_token: Option<String>, // pub error_code: Option<String>, // pub connector_metadata: Option<serde_json::Value>, // pub payment_experience: Option<PaymentExperience>, // pub payment_method_data: Option<serde_json::Value>, // pub preprocessing_step_id: Option<String>, // pub error_reason: Option<String>, // pub connector_response_reference_id: Option<String>, // pub multiple_capture_count: Option<i16>, // pub amount_capturable: i64, // pub updated_by: String, // pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, // pub authentication_data: Option<serde_json::Value>, // pub encoded_data: Option<String>, // pub unified_code: Option<String>, // pub unified_message: Option<String>, // pub net_amount: Option<i64>, // pub external_three_ds_authentication_attempted: Option<bool>, // pub authentication_connector: Option<String>, // pub authentication_id: Option<String>, // pub fingerprint_id: Option<String>, // pub charge_id: Option<String>, // pub client_source: Option<String>, // pub client_version: Option<String>, // pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, // pub profile_id: common_utils::id_type::ProfileId, // pub organization_id: common_utils::id_type::OrganizationId, // } // #[cfg(feature = "v2")] // #[allow(dead_code)] // impl PaymentAttemptBatchNew { // // Used to verify compatibility with PaymentAttemptTable // fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { // // PaymentAttemptNew { // // payment_id: self.payment_id, // // merchant_id: self.merchant_id, // // status: self.status, // // error_message: self.error_message, // // surcharge_amount: self.surcharge_amount, // // tax_amount: self.tax_amount, // // payment_method_id: self.payment_method_id, // // confirm: self.confirm, // // authentication_type: self.authentication_type, // // created_at: self.created_at, // // modified_at: self.modified_at, // // last_synced: self.last_synced, // // cancellation_reason: self.cancellation_reason, // // browser_info: self.browser_info, // // payment_token: self.payment_token, // // error_code: self.error_code, // // connector_metadata: self.connector_metadata, // // payment_experience: self.payment_experience, // // card_network: self // // .payment_method_data // // .as_ref() // // .and_then(|data| data.as_object()) // // .and_then(|card| card.get("card")) // // .and_then(|v| v.as_object()) // // .and_then(|v| v.get("card_network")) // // .and_then(|network| network.as_str()) // // .map(|network| network.to_string()), // // payment_method_data: self.payment_method_data, // // straight_through_algorithm: self.straight_through_algorithm, // // preprocessing_step_id: self.preprocessing_step_id, // // error_reason: self.error_reason, // // multiple_capture_count: self.multiple_capture_count, // // connector_response_reference_id: self.connector_response_reference_id, // // amount_capturable: self.amount_capturable, // // updated_by: self.updated_by, // // merchant_connector_id: self.merchant_connector_id, // // authentication_data: self.authentication_data, // // encoded_data: self.encoded_data, // // unified_code: self.unified_code, // // unified_message: self.unified_message, // // net_amount: self.net_amount, // // external_three_ds_authentication_attempted: self // // .external_three_ds_authentication_attempted, // // authentication_connector: self.authentication_connector, // // authentication_id: self.authentication_id, // // payment_method_billing_address_id: self.payment_method_billing_address_id, // // fingerprint_id: self.fingerprint_id, // // charge_id: self.charge_id, // // client_source: self.client_source, // // client_version: self.client_version, // // customer_acceptance: self.customer_acceptance, // // profile_id: self.profile_id, // // organization_id: self.organization_id, // // } // todo!() // } // } #[cfg(feature = "v1")] #[derive( Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptBatchNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub status: AttemptStatus, pub amount: MinorUnit, pub currency: Option<Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<PaymentMethod>, pub capture_method: Option<CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<PaymentExperience>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<ConnectorTransactionId>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<common_utils::id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, pub profile_id: common_utils::id_type::ProfileId, pub organization_id: common_utils::id_type::OrganizationId, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub processor_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub tokenization: Option<common_enums::Tokenization>, pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, pub routing_approach: Option<common_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[allow(dead_code)] impl PaymentAttemptBatchNew { // Used to verify compatibility with PaymentAttemptTable fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { PaymentAttemptNew { payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.surcharge_amount, tax_amount: self.tax_amount, payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, card_network: self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|v| v.as_object()) .and_then(|v| v.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_method_data: self.payment_method_data, encrypted_payment_method_data: self.encrypted_payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details, error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, amount_capturable: self.amount_capturable, updated_by: self.updated_by, merchant_connector_id: self.merchant_connector_id, authentication_data: self.authentication_data, encoded_data: self.encoded_data, unified_code: self.unified_code, unified_message: self.unified_message, net_amount: self.net_amount, external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data, payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, profile_id: self.profile_id, organization_id: self.organization_id, shipping_cost: self.shipping_cost, order_tax_amount: self.order_tax_amount, connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, extended_authorization_last_applied_at: self.extended_authorization_last_applied_at, capture_before: self.capture_before, card_discovery: self.card_discovery, processor_merchant_id: self.processor_merchant_id, created_by: self.created_by, setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, tokenization: self.tokenization, error_details: None, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/diesel_models/src/user/dashboard_metadata.rs
crates/diesel_models/src/user/dashboard_metadata.rs
use common_utils::id_type; use diesel::{query_builder::AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{enums, schema::dashboard_metadata}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = dashboard_metadata, check_for_backend(diesel::pg::Pg))] pub struct DashboardMetadata { pub id: i32, pub user_id: Option<String>, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub created_by: String, pub created_at: PrimitiveDateTime, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive( router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay, AsChangeset, )] #[diesel(table_name = dashboard_metadata)] pub struct DashboardMetadataNew { pub user_id: Option<String>, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub created_by: String, pub created_at: PrimitiveDateTime, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive( router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay, AsChangeset, )] #[diesel(table_name = dashboard_metadata)] pub struct DashboardMetadataUpdateInternal { pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive(Debug)] pub enum DashboardMetadataUpdate { UpdateData { data_key: enums::DashboardMetadata, data_value: Secret<serde_json::Value>, last_modified_by: String, }, } impl From<DashboardMetadataUpdate> for DashboardMetadataUpdateInternal { fn from(metadata_update: DashboardMetadataUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match metadata_update { DashboardMetadataUpdate::UpdateData { data_key, data_value, last_modified_by, } => Self { data_key, data_value, last_modified_by, last_modified_at, }, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/events/src/actix.rs
crates/events/src/actix.rs
use router_env::RequestId; use crate::EventInfo; impl EventInfo for RequestId { type Data = String; fn data(&self) -> error_stack::Result<String, crate::EventsError> { Ok(self.to_string()) } fn key(&self) -> String { "request_id".to_string() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/events/src/lib.rs
crates/events/src/lib.rs
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))] #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] //! A generic event handler system. //! This library consists of 4 parts: //! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database. //! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event. //! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events. //! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier. mod actix; use std::{collections::HashMap, sync::Arc}; use error_stack::{Result, ResultExt}; use masking::{ErasedMaskSerialize, Serialize}; use router_env::logger; use serde::Serializer; use serde_json::Value; use time::PrimitiveDateTime; /// Errors that can occur when working with events. #[derive(Debug, Clone, thiserror::Error)] pub enum EventsError { /// An error occurred when publishing the event. #[error("Generic Error")] GenericError, /// An error occurred when serializing the event. #[error("Event serialization error")] SerializationError, /// An error occurred when publishing/producing the event. #[error("Event publishing error")] PublishError, } /// An event that can be published. pub trait Event: EventInfo { /// The type of the event. type EventType; /// The timestamp of the event. fn timestamp(&self) -> PrimitiveDateTime; /// The (unique) identifier of the event. fn identifier(&self) -> String; /// The class/type of the event. This is used to group/categorize events together. fn class(&self) -> Self::EventType; /// Metadata associated with the event fn metadata(&self) -> HashMap<String, String> { HashMap::new() } } /// Hold the context information for any events #[derive(Clone)] pub struct EventContext<T, A> where A: MessagingInterface<MessageClass = T>, { message_sink: Arc<A>, metadata: HashMap<String, Value>, } /// intermediary structure to build events with in-place info. #[must_use = "make sure to call `emit` or `try_emit` to actually emit the event"] pub struct EventBuilder<T, A, E, D> where A: MessagingInterface<MessageClass = T>, E: Event<EventType = T, Data = D>, { message_sink: Arc<A>, metadata: HashMap<String, Value>, event: E, } /// A flattened event that flattens the context provided to it along with the actual event. struct FlatMapEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A); impl<T, A, E, D> EventBuilder<T, A, E, D> where A: MessagingInterface<MessageClass = T>, E: Event<EventType = T, Data = D>, { /// Add metadata to the event. pub fn with<F: ErasedMaskSerialize, G: EventInfo<Data = F> + 'static>( mut self, info: G, ) -> Self { info.data() .and_then(|i| { i.masked_serialize() .change_context(EventsError::SerializationError) }) .map_err(|e| { logger::error!("Error adding event info: {:?}", e); }) .ok() .and_then(|data| self.metadata.insert(info.key(), data)); self } /// Emit the event and log any errors. pub fn emit(self) { self.try_emit() .map_err(|e| { logger::error!("Error emitting event: {:?}", e); }) .ok(); } /// Emit the event. pub fn try_emit(self) -> Result<(), EventsError> { let ts = self.event.timestamp(); let metadata = self.event.metadata(); self.message_sink .send_message(FlatMapEvent(self.metadata, self.event), metadata, ts) } } impl<T, A> Serialize for FlatMapEvent<T, A> where A: Event<EventType = T>, { fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> where S: Serializer, { let mut serialize_map: HashMap<_, _> = self .0 .iter() .filter_map(|(k, v)| Some((k.clone(), v.masked_serialize().ok()?))) .collect(); match self.1.data().map(|i| i.masked_serialize()) { Ok(Ok(Value::Object(map))) => { for (k, v) in map.into_iter() { serialize_map.insert(k, v); } } Ok(Ok(i)) => { serialize_map.insert(self.1.key(), i); } i => { logger::error!("Error serializing event: {:?}", i); } }; serialize_map.serialize(serializer) } } impl<T, A> EventContext<T, A> where A: MessagingInterface<MessageClass = T>, { /// Create a new event context. pub fn new(message_sink: A) -> Self { Self { message_sink: Arc::new(message_sink), metadata: HashMap::new(), } } /// Add metadata to the event context. #[track_caller] pub fn record_info<G: ErasedMaskSerialize, E: EventInfo<Data = G> + 'static>( &mut self, info: E, ) { match info.data().and_then(|i| { i.masked_serialize() .change_context(EventsError::SerializationError) }) { Ok(data) => { self.metadata.insert(info.key(), data); } Err(e) => { logger::error!("Error recording event info: {:?}", e); } } } /// Emit an event. pub fn try_emit<E: Event<EventType = T>>(&self, event: E) -> Result<(), EventsError> { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } .try_emit() } /// Emit an event. pub fn emit<D, E: Event<EventType = T, Data = D>>(&self, event: E) { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } .emit() } /// Create an event builder. pub fn event<D, E: Event<EventType = T, Data = D>>( &self, event: E, ) -> EventBuilder<T, A, E, D> { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } } } /// Add information/metadata to the current context of an event. pub trait EventInfo { /// The data that is sent with the event. type Data: ErasedMaskSerialize; /// The data that is sent with the event. fn data(&self) -> Result<Self::Data, EventsError>; /// The key identifying the data for an event. fn key(&self) -> String; } impl EventInfo for (String, String) { type Data = String; fn data(&self) -> Result<String, EventsError> { Ok(self.1.clone()) } fn key(&self) -> String { self.0.clone() } } /// A messaging interface for sending messages/events. /// This can be implemented for any messaging system, such as a message queue, a logger, or a database. pub trait MessagingInterface { /// The type of the event used for categorization by the event publisher. type MessageClass; /// Send a message that follows the defined message class. fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize; } /// A message that can be sent. pub trait Message { /// The type of the event used for categorization by the event publisher. type Class; /// The type of the event used for categorization by the event publisher. fn get_message_class(&self) -> Self::Class; /// The (unique) identifier of the event. fn identifier(&self) -> String; } impl<T, A> Message for FlatMapEvent<T, A> where A: Event<EventType = T>, { type Class = T; fn get_message_class(&self) -> Self::Class { self.1.class() } fn identifier(&self) -> String { self.1.identifier() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/kgraph_utils/src/lib.rs
crates/kgraph_utils/src/lib.rs
pub mod error; pub mod mca; pub mod transformers; pub mod types;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/kgraph_utils/src/error.rs
crates/kgraph_utils/src/error.rs
#[cfg(feature = "v2")] use common_enums::connector_enums; use euclid::{dssa::types::AnalysisErrorType, frontend::dir}; #[derive(Debug, thiserror::Error, serde::Serialize)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum KgraphError { #[error("Invalid connector name encountered: '{0}'")] InvalidConnectorName( #[cfg(feature = "v1")] String, #[cfg(feature = "v2")] connector_enums::Connector, ), #[error("Error in domain creation")] DomainCreationError, #[error("There was an error constructing the graph: {0}")] GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>), #[error("There was an error constructing the context")] ContextConstructionError(Box<AnalysisErrorType>), #[error("there was an unprecedented indexing error")] IndexingError, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/kgraph_utils/src/types.rs
crates/kgraph_utils/src/types.rs
use std::collections::{HashMap, HashSet}; use api_models::enums as api_enums; use serde::Deserialize; #[derive(Debug, Deserialize, Clone, Default)] pub struct CountryCurrencyFilter { pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>, pub default_configs: Option<PaymentMethodFilters>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] pub enum PaymentMethodFilterKey { PaymentMethodType(api_enums::PaymentMethodType), CardNetwork(api_enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { pub currency: Option<HashSet<api_enums::Currency>>, pub country: Option<HashSet<api_enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { pub capture_method: Option<api_enums::CaptureMethod>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/kgraph_utils/src/transformers.rs
crates/kgraph_utils/src/transformers.rs
use api_models::enums as api_enums; use euclid::{ backend::BackendInput, dirval, dssa::types::AnalysisErrorType, frontend::{ast, dir}, types::{NumValue, StrValue}, }; use crate::error::KgraphError; pub trait IntoContext { fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError>; } impl IntoContext for BackendInput { fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError> { let mut ctx: Vec<dir::DirValue> = Vec::new(); ctx.push(dir::DirValue::PaymentAmount(NumValue { number: self.payment.amount, refinement: None, })); ctx.push(dir::DirValue::PaymentCurrency(self.payment.currency)); if let Some(auth_type) = self.payment.authentication_type { ctx.push(dir::DirValue::AuthenticationType(auth_type)); } if let Some(capture_method) = self.payment.capture_method { ctx.push(dir::DirValue::CaptureMethod(capture_method)); } if let Some(business_country) = self.payment.business_country { ctx.push(dir::DirValue::BusinessCountry(business_country)); } if let Some(business_label) = self.payment.business_label { ctx.push(dir::DirValue::BusinessLabel(StrValue { value: business_label, })); } if let Some(billing_country) = self.payment.billing_country { ctx.push(dir::DirValue::BillingCountry(billing_country)); } if let Some(payment_method) = self.payment_method.payment_method { ctx.push(dir::DirValue::PaymentMethod(payment_method)); } if let (Some(pm_type), Some(payment_method)) = ( self.payment_method.payment_method_type, self.payment_method.payment_method, ) { ctx.push((pm_type, payment_method).into_dir_value()?) } if let Some(card_network) = self.payment_method.card_network { ctx.push(dir::DirValue::CardNetwork(card_network)); } if let Some(setup_future_usage) = self.payment.setup_future_usage { ctx.push(dir::DirValue::SetupFutureUsage(setup_future_usage)); } if let Some(mandate_acceptance_type) = self.mandate.mandate_acceptance_type { ctx.push(dir::DirValue::MandateAcceptanceType( mandate_acceptance_type, )); } if let Some(mandate_type) = self.mandate.mandate_type { ctx.push(dir::DirValue::MandateType(mandate_type)); } if let Some(payment_type) = self.mandate.payment_type { ctx.push(dir::DirValue::PaymentType(payment_type)); } Ok(ctx) } } pub trait IntoDirValue { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError>; } impl IntoDirValue for ast::ConnectorChoice { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { Ok(dir::DirValue::Connector(Box::new(self))) } } impl IntoDirValue for api_enums::PaymentMethod { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::Card => Ok(dirval!(PaymentMethod = Card)), Self::Wallet => Ok(dirval!(PaymentMethod = Wallet)), Self::PayLater => Ok(dirval!(PaymentMethod = PayLater)), Self::BankRedirect => Ok(dirval!(PaymentMethod = BankRedirect)), Self::Crypto => Ok(dirval!(PaymentMethod = Crypto)), Self::BankDebit => Ok(dirval!(PaymentMethod = BankDebit)), Self::BankTransfer => Ok(dirval!(PaymentMethod = BankTransfer)), Self::Reward => Ok(dirval!(PaymentMethod = Reward)), Self::RealTimePayment => Ok(dirval!(PaymentMethod = RealTimePayment)), Self::Upi => Ok(dirval!(PaymentMethod = Upi)), Self::Voucher => Ok(dirval!(PaymentMethod = Voucher)), Self::GiftCard => Ok(dirval!(PaymentMethod = GiftCard)), Self::CardRedirect => Ok(dirval!(PaymentMethod = CardRedirect)), Self::OpenBanking => Ok(dirval!(PaymentMethod = OpenBanking)), Self::MobilePayment => Ok(dirval!(PaymentMethod = MobilePayment)), Self::NetworkToken => Ok(dirval!(PaymentMethod = NetworkToken)), } } } impl IntoDirValue for api_enums::AuthenticationType { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::ThreeDs => Ok(dirval!(AuthenticationType = ThreeDs)), Self::NoThreeDs => Ok(dirval!(AuthenticationType = NoThreeDs)), } } } impl IntoDirValue for api_enums::FutureUsage { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::OnSession => Ok(dirval!(SetupFutureUsage = OnSession)), Self::OffSession => Ok(dirval!(SetupFutureUsage = OffSession)), } } } impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self.0 { api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)), api_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), #[cfg(feature = "v2")] api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), api_enums::PaymentMethodType::Payjustnow => Ok(dirval!(PayLaterType = Payjustnow)), api_enums::PaymentMethodType::AfterpayClearpay => { Ok(dirval!(PayLaterType = AfterpayClearpay)) } api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), api_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)), api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), api_enums::PaymentMethodType::CryptoCurrency => { Ok(dirval!(CryptoType = CryptoCurrency)) } api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), api_enums::PaymentMethodType::Ach => match self.1 { api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)), api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)), api_enums::PaymentMethod::BankRedirect | api_enums::PaymentMethod::Card | api_enums::PaymentMethod::CardRedirect | api_enums::PaymentMethod::PayLater | api_enums::PaymentMethod::Wallet | api_enums::PaymentMethod::Crypto | api_enums::PaymentMethod::Reward | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::MobilePayment | api_enums::PaymentMethod::Voucher | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard | api_enums::PaymentMethod::NetworkToken => { Err(KgraphError::ContextConstructionError(Box::new( AnalysisErrorType::NotSupported, ))) } }, api_enums::PaymentMethodType::Bacs => match self.1 { api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)), api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)), api_enums::PaymentMethod::BankRedirect | api_enums::PaymentMethod::Card | api_enums::PaymentMethod::CardRedirect | api_enums::PaymentMethod::PayLater | api_enums::PaymentMethod::Wallet | api_enums::PaymentMethod::Crypto | api_enums::PaymentMethod::Reward | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::MobilePayment | api_enums::PaymentMethod::Voucher | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard | api_enums::PaymentMethod::NetworkToken => { Err(KgraphError::ContextConstructionError(Box::new( AnalysisErrorType::NotSupported, ))) } }, api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)), api_enums::PaymentMethodType::SepaGuarenteedDebit => { Ok(dirval!(BankDebitType = SepaGuarenteedDebit)) } api_enums::PaymentMethodType::SepaBankTransfer => { Ok(dirval!(BankTransferType = SepaBankTransfer)) } api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)), api_enums::PaymentMethodType::BancontactCard => { Ok(dirval!(BankRedirectType = BancontactCard)) } api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)), api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)), api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)), api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)), api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)), api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)), api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)), api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)), api_enums::PaymentMethodType::OnlineBankingCzechRepublic => { Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic)) } api_enums::PaymentMethodType::OnlineBankingFinland => { Ok(dirval!(BankRedirectType = OnlineBankingFinland)) } api_enums::PaymentMethodType::OnlineBankingPoland => { Ok(dirval!(BankRedirectType = OnlineBankingPoland)) } api_enums::PaymentMethodType::OnlineBankingSlovakia => { Ok(dirval!(BankRedirectType = OnlineBankingSlovakia)) } api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)), api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)), api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)), api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)), api_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)), api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)), api_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)), api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)), api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)), api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), api_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)), api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)), api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)), api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)), api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)), api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)), api_enums::PaymentMethodType::OnlineBankingFpx => { Ok(dirval!(BankRedirectType = OnlineBankingFpx)) } api_enums::PaymentMethodType::LocalBankRedirect => { Ok(dirval!(BankRedirectType = LocalBankRedirect)) } api_enums::PaymentMethodType::OnlineBankingThailand => { Ok(dirval!(BankRedirectType = OnlineBankingThailand)) } api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)), api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)), api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)), api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)), api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)), api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)), api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)), api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)), api_enums::PaymentMethodType::BcaBankTransfer => { Ok(dirval!(BankTransferType = BcaBankTransfer)) } api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)), api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)), api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)), api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), api_enums::PaymentMethodType::LocalBankTransfer => { Ok(dirval!(BankTransferType = LocalBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransfer => { Ok(dirval!(BankTransferType = InstantBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransferFinland => { Ok(dirval!(BankTransferType = InstantBankTransferFinland)) } api_enums::PaymentMethodType::InstantBankTransferPoland => { Ok(dirval!(BankTransferType = InstantBankTransferPoland)) } api_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)), api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)), api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)), api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)), api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)), api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)), api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)), api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)), api_enums::PaymentMethodType::BhnCardNetwork => { Ok(dirval!(GiftCardType = BhnCardNetwork)) } api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)), api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)), api_enums::PaymentMethodType::OpenBankingUk => { Ok(dirval!(BankRedirectType = OpenBankingUk)) } api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)), api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), api_enums::PaymentMethodType::CardRedirect => { Ok(dirval!(CardRedirectType = CardRedirect)) } api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)), api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), api_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } api_enums::PaymentMethodType::IndonesianBankTransfer => { Ok(dirval!(BankTransferType = IndonesianBankTransfer)) } api_enums::PaymentMethodType::OpenBanking => { Ok(dirval!(BankRedirectType = OpenBanking)) } api_enums::PaymentMethodType::NetworkToken => { Ok(dirval!(NetworkTokenType = NetworkToken)) } } } } impl IntoDirValue for api_enums::CardNetwork { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::Visa => Ok(dirval!(CardNetwork = Visa)), Self::Mastercard => Ok(dirval!(CardNetwork = Mastercard)), Self::AmericanExpress => Ok(dirval!(CardNetwork = AmericanExpress)), Self::JCB => Ok(dirval!(CardNetwork = JCB)), Self::DinersClub => Ok(dirval!(CardNetwork = DinersClub)), Self::Discover => Ok(dirval!(CardNetwork = Discover)), Self::CartesBancaires => Ok(dirval!(CardNetwork = CartesBancaires)), Self::UnionPay => Ok(dirval!(CardNetwork = UnionPay)), Self::Interac => Ok(dirval!(CardNetwork = Interac)), Self::RuPay => Ok(dirval!(CardNetwork = RuPay)), Self::Maestro => Ok(dirval!(CardNetwork = Maestro)), Self::Star => Ok(dirval!(CardNetwork = Star)), Self::Accel => Ok(dirval!(CardNetwork = Accel)), Self::Pulse => Ok(dirval!(CardNetwork = Pulse)), Self::Nyce => Ok(dirval!(CardNetwork = Nyce)), } } } impl IntoDirValue for api_enums::Currency { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::AED => Ok(dirval!(PaymentCurrency = AED)), Self::AFN => Ok(dirval!(PaymentCurrency = AFN)), Self::ALL => Ok(dirval!(PaymentCurrency = ALL)), Self::AMD => Ok(dirval!(PaymentCurrency = AMD)), Self::ANG => Ok(dirval!(PaymentCurrency = ANG)), Self::AOA => Ok(dirval!(PaymentCurrency = AOA)), Self::ARS => Ok(dirval!(PaymentCurrency = ARS)), Self::AUD => Ok(dirval!(PaymentCurrency = AUD)), Self::AWG => Ok(dirval!(PaymentCurrency = AWG)), Self::AZN => Ok(dirval!(PaymentCurrency = AZN)), Self::BAM => Ok(dirval!(PaymentCurrency = BAM)), Self::BBD => Ok(dirval!(PaymentCurrency = BBD)), Self::BDT => Ok(dirval!(PaymentCurrency = BDT)), Self::BGN => Ok(dirval!(PaymentCurrency = BGN)), Self::BHD => Ok(dirval!(PaymentCurrency = BHD)), Self::BIF => Ok(dirval!(PaymentCurrency = BIF)), Self::BMD => Ok(dirval!(PaymentCurrency = BMD)), Self::BND => Ok(dirval!(PaymentCurrency = BND)), Self::BOB => Ok(dirval!(PaymentCurrency = BOB)), Self::BRL => Ok(dirval!(PaymentCurrency = BRL)), Self::BSD => Ok(dirval!(PaymentCurrency = BSD)), Self::BTN => Ok(dirval!(PaymentCurrency = BTN)), Self::BWP => Ok(dirval!(PaymentCurrency = BWP)), Self::BYN => Ok(dirval!(PaymentCurrency = BYN)), Self::BZD => Ok(dirval!(PaymentCurrency = BZD)), Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), Self::CDF => Ok(dirval!(PaymentCurrency = CDF)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), Self::CLF => Ok(dirval!(PaymentCurrency = CLF)), Self::CLP => Ok(dirval!(PaymentCurrency = CLP)), Self::CNY => Ok(dirval!(PaymentCurrency = CNY)), Self::COP => Ok(dirval!(PaymentCurrency = COP)), Self::CRC => Ok(dirval!(PaymentCurrency = CRC)), Self::CUC => Ok(dirval!(PaymentCurrency = CUC)), Self::CUP => Ok(dirval!(PaymentCurrency = CUP)), Self::CVE => Ok(dirval!(PaymentCurrency = CVE)), Self::CZK => Ok(dirval!(PaymentCurrency = CZK)), Self::DJF => Ok(dirval!(PaymentCurrency = DJF)), Self::DKK => Ok(dirval!(PaymentCurrency = DKK)), Self::DOP => Ok(dirval!(PaymentCurrency = DOP)), Self::DZD => Ok(dirval!(PaymentCurrency = DZD)), Self::EGP => Ok(dirval!(PaymentCurrency = EGP)), Self::ERN => Ok(dirval!(PaymentCurrency = ERN)), Self::ETB => Ok(dirval!(PaymentCurrency = ETB)), Self::EUR => Ok(dirval!(PaymentCurrency = EUR)), Self::FJD => Ok(dirval!(PaymentCurrency = FJD)), Self::FKP => Ok(dirval!(PaymentCurrency = FKP)), Self::GBP => Ok(dirval!(PaymentCurrency = GBP)), Self::GEL => Ok(dirval!(PaymentCurrency = GEL)), Self::GHS => Ok(dirval!(PaymentCurrency = GHS)), Self::GIP => Ok(dirval!(PaymentCurrency = GIP)), Self::GMD => Ok(dirval!(PaymentCurrency = GMD)), Self::GNF => Ok(dirval!(PaymentCurrency = GNF)), Self::GTQ => Ok(dirval!(PaymentCurrency = GTQ)), Self::GYD => Ok(dirval!(PaymentCurrency = GYD)), Self::HKD => Ok(dirval!(PaymentCurrency = HKD)), Self::HNL => Ok(dirval!(PaymentCurrency = HNL)), Self::HRK => Ok(dirval!(PaymentCurrency = HRK)), Self::HTG => Ok(dirval!(PaymentCurrency = HTG)), Self::HUF => Ok(dirval!(PaymentCurrency = HUF)), Self::IDR => Ok(dirval!(PaymentCurrency = IDR)), Self::ILS => Ok(dirval!(PaymentCurrency = ILS)), Self::INR => Ok(dirval!(PaymentCurrency = INR)), Self::IQD => Ok(dirval!(PaymentCurrency = IQD)), Self::IRR => Ok(dirval!(PaymentCurrency = IRR)), Self::ISK => Ok(dirval!(PaymentCurrency = ISK)), Self::JMD => Ok(dirval!(PaymentCurrency = JMD)), Self::JOD => Ok(dirval!(PaymentCurrency = JOD)), Self::JPY => Ok(dirval!(PaymentCurrency = JPY)), Self::KES => Ok(dirval!(PaymentCurrency = KES)), Self::KGS => Ok(dirval!(PaymentCurrency = KGS)), Self::KHR => Ok(dirval!(PaymentCurrency = KHR)), Self::KMF => Ok(dirval!(PaymentCurrency = KMF)), Self::KPW => Ok(dirval!(PaymentCurrency = KPW)), Self::KRW => Ok(dirval!(PaymentCurrency = KRW)), Self::KWD => Ok(dirval!(PaymentCurrency = KWD)), Self::KYD => Ok(dirval!(PaymentCurrency = KYD)), Self::KZT => Ok(dirval!(PaymentCurrency = KZT)), Self::LAK => Ok(dirval!(PaymentCurrency = LAK)), Self::LBP => Ok(dirval!(PaymentCurrency = LBP)), Self::LKR => Ok(dirval!(PaymentCurrency = LKR)), Self::LRD => Ok(dirval!(PaymentCurrency = LRD)), Self::LSL => Ok(dirval!(PaymentCurrency = LSL)), Self::LYD => Ok(dirval!(PaymentCurrency = LYD)), Self::MAD => Ok(dirval!(PaymentCurrency = MAD)), Self::MDL => Ok(dirval!(PaymentCurrency = MDL)), Self::MGA => Ok(dirval!(PaymentCurrency = MGA)), Self::MKD => Ok(dirval!(PaymentCurrency = MKD)), Self::MMK => Ok(dirval!(PaymentCurrency = MMK)), Self::MNT => Ok(dirval!(PaymentCurrency = MNT)), Self::MOP => Ok(dirval!(PaymentCurrency = MOP)), Self::MRU => Ok(dirval!(PaymentCurrency = MRU)), Self::MUR => Ok(dirval!(PaymentCurrency = MUR)), Self::MVR => Ok(dirval!(PaymentCurrency = MVR)), Self::MWK => Ok(dirval!(PaymentCurrency = MWK)), Self::MXN => Ok(dirval!(PaymentCurrency = MXN)), Self::MYR => Ok(dirval!(PaymentCurrency = MYR)), Self::MZN => Ok(dirval!(PaymentCurrency = MZN)), Self::NAD => Ok(dirval!(PaymentCurrency = NAD)), Self::NGN => Ok(dirval!(PaymentCurrency = NGN)), Self::NIO => Ok(dirval!(PaymentCurrency = NIO)), Self::NOK => Ok(dirval!(PaymentCurrency = NOK)), Self::NPR => Ok(dirval!(PaymentCurrency = NPR)), Self::NZD => Ok(dirval!(PaymentCurrency = NZD)), Self::OMR => Ok(dirval!(PaymentCurrency = OMR)), Self::PAB => Ok(dirval!(PaymentCurrency = PAB)), Self::PEN => Ok(dirval!(PaymentCurrency = PEN)), Self::PGK => Ok(dirval!(PaymentCurrency = PGK)), Self::PHP => Ok(dirval!(PaymentCurrency = PHP)), Self::PKR => Ok(dirval!(PaymentCurrency = PKR)), Self::PLN => Ok(dirval!(PaymentCurrency = PLN)), Self::PYG => Ok(dirval!(PaymentCurrency = PYG)), Self::QAR => Ok(dirval!(PaymentCurrency = QAR)), Self::RON => Ok(dirval!(PaymentCurrency = RON)), Self::RSD => Ok(dirval!(PaymentCurrency = RSD)), Self::RUB => Ok(dirval!(PaymentCurrency = RUB)), Self::RWF => Ok(dirval!(PaymentCurrency = RWF)), Self::SAR => Ok(dirval!(PaymentCurrency = SAR)), Self::SBD => Ok(dirval!(PaymentCurrency = SBD)), Self::SCR => Ok(dirval!(PaymentCurrency = SCR)), Self::SDG => Ok(dirval!(PaymentCurrency = SDG)), Self::SEK => Ok(dirval!(PaymentCurrency = SEK)), Self::SGD => Ok(dirval!(PaymentCurrency = SGD)), Self::SHP => Ok(dirval!(PaymentCurrency = SHP)), Self::SLE => Ok(dirval!(PaymentCurrency = SLE)), Self::SLL => Ok(dirval!(PaymentCurrency = SLL)), Self::SOS => Ok(dirval!(PaymentCurrency = SOS)), Self::SRD => Ok(dirval!(PaymentCurrency = SRD)), Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), Self::STD => Ok(dirval!(PaymentCurrency = STD)), Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), Self::SYP => Ok(dirval!(PaymentCurrency = SYP)), Self::SZL => Ok(dirval!(PaymentCurrency = SZL)), Self::THB => Ok(dirval!(PaymentCurrency = THB)), Self::TJS => Ok(dirval!(PaymentCurrency = TJS)), Self::TMT => Ok(dirval!(PaymentCurrency = TMT)), Self::TND => Ok(dirval!(PaymentCurrency = TND)), Self::TOP => Ok(dirval!(PaymentCurrency = TOP)), Self::TRY => Ok(dirval!(PaymentCurrency = TRY)), Self::TTD => Ok(dirval!(PaymentCurrency = TTD)), Self::TWD => Ok(dirval!(PaymentCurrency = TWD)), Self::TZS => Ok(dirval!(PaymentCurrency = TZS)), Self::UAH => Ok(dirval!(PaymentCurrency = UAH)), Self::UGX => Ok(dirval!(PaymentCurrency = UGX)), Self::USD => Ok(dirval!(PaymentCurrency = USD)), Self::UYU => Ok(dirval!(PaymentCurrency = UYU)), Self::UZS => Ok(dirval!(PaymentCurrency = UZS)), Self::VES => Ok(dirval!(PaymentCurrency = VES)), Self::VND => Ok(dirval!(PaymentCurrency = VND)), Self::VUV => Ok(dirval!(PaymentCurrency = VUV)), Self::WST => Ok(dirval!(PaymentCurrency = WST)), Self::XAF => Ok(dirval!(PaymentCurrency = XAF)), Self::XCD => Ok(dirval!(PaymentCurrency = XCD)), Self::XOF => Ok(dirval!(PaymentCurrency = XOF)), Self::XPF => Ok(dirval!(PaymentCurrency = XPF)), Self::YER => Ok(dirval!(PaymentCurrency = YER)), Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)), Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)), Self::ZWL => Ok(dirval!(PaymentCurrency = ZWL)), } } } pub fn get_dir_country_dir_value(c: api_enums::Country) -> dir::enums::Country { match c { api_enums::Country::Afghanistan => dir::enums::Country::Afghanistan, api_enums::Country::AlandIslands => dir::enums::Country::AlandIslands, api_enums::Country::Albania => dir::enums::Country::Albania, api_enums::Country::Algeria => dir::enums::Country::Algeria, api_enums::Country::AmericanSamoa => dir::enums::Country::AmericanSamoa, api_enums::Country::Andorra => dir::enums::Country::Andorra, api_enums::Country::Angola => dir::enums::Country::Angola, api_enums::Country::Anguilla => dir::enums::Country::Anguilla, api_enums::Country::Antarctica => dir::enums::Country::Antarctica, api_enums::Country::AntiguaAndBarbuda => dir::enums::Country::AntiguaAndBarbuda, api_enums::Country::Argentina => dir::enums::Country::Argentina, api_enums::Country::Armenia => dir::enums::Country::Armenia, api_enums::Country::Aruba => dir::enums::Country::Aruba, api_enums::Country::Australia => dir::enums::Country::Australia, api_enums::Country::Austria => dir::enums::Country::Austria, api_enums::Country::Azerbaijan => dir::enums::Country::Azerbaijan, api_enums::Country::Bahamas => dir::enums::Country::Bahamas, api_enums::Country::Bahrain => dir::enums::Country::Bahrain, api_enums::Country::Bangladesh => dir::enums::Country::Bangladesh, api_enums::Country::Barbados => dir::enums::Country::Barbados, api_enums::Country::Belarus => dir::enums::Country::Belarus, api_enums::Country::Belgium => dir::enums::Country::Belgium, api_enums::Country::Belize => dir::enums::Country::Belize, api_enums::Country::Benin => dir::enums::Country::Benin, api_enums::Country::Bermuda => dir::enums::Country::Bermuda, api_enums::Country::Bhutan => dir::enums::Country::Bhutan, api_enums::Country::BoliviaPlurinationalState => { dir::enums::Country::BoliviaPlurinationalState } api_enums::Country::BonaireSintEustatiusAndSaba => { dir::enums::Country::BonaireSintEustatiusAndSaba } api_enums::Country::BosniaAndHerzegovina => dir::enums::Country::BosniaAndHerzegovina, api_enums::Country::Botswana => dir::enums::Country::Botswana, api_enums::Country::BouvetIsland => dir::enums::Country::BouvetIsland, api_enums::Country::Brazil => dir::enums::Country::Brazil, api_enums::Country::BritishIndianOceanTerritory => {
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/kgraph_utils/src/mca.rs
crates/kgraph_utils/src/mca.rs
#[cfg(feature = "v1")] use std::str::FromStr; #[cfg(feature = "v1")] use api_models::payment_methods::RequestPaymentMethodTypes; use api_models::{admin as admin_api, enums as api_enums, refunds::MinorUnit}; use euclid::{ dirval, frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; use hyperswitch_constraint_graph as cgraph; use strum::IntoEnumIterator; use crate::{error::KgraphError, transformers::IntoDirValue, types as kgraph_types}; pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount"; // #[cfg(feature = "v1")] fn get_dir_value_payment_method( from: api_enums::PaymentMethodType, ) -> Result<dir::DirValue, KgraphError> { match from { api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)), api_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), #[cfg(feature = "v2")] api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), api_enums::PaymentMethodType::Payjustnow => Ok(dirval!(PayLaterType = Payjustnow)), api_enums::PaymentMethodType::AfterpayClearpay => { Ok(dirval!(PayLaterType = AfterpayClearpay)) } api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), api_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)), api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), api_enums::PaymentMethodType::CryptoCurrency => Ok(dirval!(CryptoType = CryptoCurrency)), api_enums::PaymentMethodType::Ach => Ok(dirval!(BankDebitType = Ach)), api_enums::PaymentMethodType::Bacs => Ok(dirval!(BankDebitType = Bacs)), api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)), api_enums::PaymentMethodType::SepaGuarenteedDebit => { Ok(dirval!(BankDebitType = SepaGuarenteedDebit)) } api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)), api_enums::PaymentMethodType::BancontactCard => { Ok(dirval!(BankRedirectType = BancontactCard)) } api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)), api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)), api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)), api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)), api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)), api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)), api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)), api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)), api_enums::PaymentMethodType::OnlineBankingCzechRepublic => { Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic)) } api_enums::PaymentMethodType::OnlineBankingFinland => { Ok(dirval!(BankRedirectType = OnlineBankingFinland)) } api_enums::PaymentMethodType::OnlineBankingPoland => { Ok(dirval!(BankRedirectType = OnlineBankingPoland)) } api_enums::PaymentMethodType::OnlineBankingSlovakia => { Ok(dirval!(BankRedirectType = OnlineBankingSlovakia)) } api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)), api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)), api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)), api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)), api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)), api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)), api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)), api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)), api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)), api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)), api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)), api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)), api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)), api_enums::PaymentMethodType::OnlineBankingFpx => { Ok(dirval!(BankRedirectType = OnlineBankingFpx)) } api_enums::PaymentMethodType::OnlineBankingThailand => { Ok(dirval!(BankRedirectType = OnlineBankingThailand)) } api_enums::PaymentMethodType::LocalBankRedirect => { Ok(dirval!(BankRedirectType = LocalBankRedirect)) } api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)), api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)), api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)), api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)), api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)), api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)), api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)), api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)), api_enums::PaymentMethodType::BcaBankTransfer => { Ok(dirval!(BankTransferType = BcaBankTransfer)) } api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)), api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)), api_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)), api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)), api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), api_enums::PaymentMethodType::LocalBankTransfer => { Ok(dirval!(BankTransferType = LocalBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransfer => { Ok(dirval!(BankTransferType = InstantBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransferFinland => { Ok(dirval!(BankTransferType = InstantBankTransferFinland)) } api_enums::PaymentMethodType::InstantBankTransferPoland => { Ok(dirval!(BankTransferType = InstantBankTransferPoland)) } api_enums::PaymentMethodType::SepaBankTransfer => { Ok(dirval!(BankTransferType = SepaBankTransfer)) } api_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } api_enums::PaymentMethodType::IndonesianBankTransfer => { Ok(dirval!(BankTransferType = IndonesianBankTransfer)) } api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)), api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)), api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)), api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)), api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)), api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)), api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)), api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)), api_enums::PaymentMethodType::BhnCardNetwork => Ok(dirval!(GiftCardType = BhnCardNetwork)), api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)), api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)), api_enums::PaymentMethodType::OpenBankingUk => { Ok(dirval!(BankRedirectType = OpenBankingUk)) } api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)), api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)), api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), api_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)), api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)), api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), api_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), api_enums::PaymentMethodType::OpenBanking => Ok(dirval!(BankRedirectType = OpenBanking)), api_enums::PaymentMethodType::NetworkToken => Ok(dirval!(NetworkTokenType = NetworkToken)), } } #[cfg(feature = "v2")] fn compile_request_pm_types( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, pm_types: common_types::payment_methods::RequestPaymentMethodTypes, pm: api_enums::PaymentMethod, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let pmt_info = "PaymentMethodType"; let pmt_id = builder.make_value_node( (pm_types.payment_method_subtype, pm) .into_dir_value() .map(Into::into)?, Some(pmt_info), None::<()>, ); agg_nodes.push(( pmt_id, cgraph::Relation::Positive, match pm_types.payment_method_subtype { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { cgraph::Strength::Weak } _ => cgraph::Strength::Strong, }, )); if let Some(card_networks) = pm_types.card_networks { if !card_networks.is_empty() { let dir_vals: Vec<dir::DirValue> = card_networks .into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>()?; let card_network_info = "Card Networks"; let card_network_id = builder .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_network_id, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } let currencies_data = pm_types .accepted_currencies .and_then(|accepted_currencies| match accepted_currencies { common_types::payment_methods::AcceptedCurrencies::EnableOnly(curr) if !curr.is_empty() => { Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Positive, )) } common_types::payment_methods::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => { Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Negative, )) } _ => None, }); if let Some((currencies, relation)) = currencies_data { let accepted_currencies_info = "Accepted Currencies"; let accepted_currencies_id = builder .make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong)); } let mut amount_nodes = Vec::with_capacity(2); if let Some(min_amt) = pm_types.minimum_amount { let num_val = NumValue { number: min_amt, refinement: Some(NumValueRefinement::GreaterThanEqual), }; let min_amt_info = "Minimum Amount"; let min_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(min_amt_info), None::<()>, ); amount_nodes.push(min_amt_id); } if let Some(max_amt) = pm_types.maximum_amount { let num_val = NumValue { number: max_amt, refinement: Some(NumValueRefinement::LessThanEqual), }; let max_amt_info = "Maximum Amount"; let max_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(max_amt_info), None::<()>, ); amount_nodes.push(max_amt_id); } if !amount_nodes.is_empty() { let zero_num_val = NumValue { number: MinorUnit::zero(), refinement: None, }; let zero_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(zero_num_val).into(), Some("zero_amount"), None::<()>, ); let or_node_neighbor_id = if amount_nodes.len() == 1 { amount_nodes .first() .copied() .ok_or(KgraphError::IndexingError)? } else { let nodes = amount_nodes .iter() .copied() .map(|node_id| { ( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ) }) .collect::<Vec<_>>(); builder .make_all_aggregator( &nodes, Some("amount_constraint_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)? }; let any_aggregator = builder .make_any_aggregator( &[ ( zero_amt_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( or_node_neighbor_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some("zero_plus_limits_amount_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( any_aggregator, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType"; builder .make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } #[cfg(feature = "v1")] fn compile_request_pm_types( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, pm_types: RequestPaymentMethodTypes, pm: api_enums::PaymentMethod, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let pmt_info = "PaymentMethodType"; let pmt_id = builder.make_value_node( (pm_types.payment_method_type, pm) .into_dir_value() .map(Into::into)?, Some(pmt_info), None::<()>, ); agg_nodes.push(( pmt_id, cgraph::Relation::Positive, match pm_types.payment_method_type { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { cgraph::Strength::Weak } _ => cgraph::Strength::Strong, }, )); if let Some(card_networks) = pm_types.card_networks { if !card_networks.is_empty() { let dir_vals: Vec<dir::DirValue> = card_networks .into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>()?; let card_network_info = "Card Networks"; let card_network_id = builder .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_network_id, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } let currencies_data = pm_types .accepted_currencies .and_then(|accepted_currencies| match accepted_currencies { admin_api::AcceptedCurrencies::EnableOnly(curr) if !curr.is_empty() => Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Positive, )), admin_api::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Negative, )), _ => None, }); if let Some((currencies, relation)) = currencies_data { let accepted_currencies_info = "Accepted Currencies"; let accepted_currencies_id = builder .make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong)); } let mut amount_nodes = Vec::with_capacity(2); if let Some(min_amt) = pm_types.minimum_amount { let num_val = NumValue { number: min_amt, refinement: Some(NumValueRefinement::GreaterThanEqual), }; let min_amt_info = "Minimum Amount"; let min_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(min_amt_info), None::<()>, ); amount_nodes.push(min_amt_id); } if let Some(max_amt) = pm_types.maximum_amount { let num_val = NumValue { number: max_amt, refinement: Some(NumValueRefinement::LessThanEqual), }; let max_amt_info = "Maximum Amount"; let max_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(max_amt_info), None::<()>, ); amount_nodes.push(max_amt_id); } if !amount_nodes.is_empty() { let zero_num_val = NumValue { number: MinorUnit::zero(), refinement: None, }; let zero_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(zero_num_val).into(), Some("zero_amount"), None::<()>, ); let or_node_neighbor_id = if amount_nodes.len() == 1 { amount_nodes .first() .copied() .ok_or(KgraphError::IndexingError)? } else { let nodes = amount_nodes .iter() .copied() .map(|node_id| { ( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ) }) .collect::<Vec<_>>(); builder .make_all_aggregator( &nodes, Some("amount_constraint_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)? }; let any_aggregator = builder .make_any_aggregator( &[ ( zero_amt_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( or_node_neighbor_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some("zero_plus_limits_amount_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( any_aggregator, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType"; builder .make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } #[cfg(feature = "v2")] fn compile_payment_method_enabled( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, enabled: common_types::payment_methods::PaymentMethodsEnabled, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let agg_id = if !enabled .payment_method_subtypes .as_ref() .map(|v| v.is_empty()) .unwrap_or(true) { let pm_info = "PaymentMethod"; let pm_id = builder.make_value_node( enabled .payment_method_type .into_dir_value() .map(Into::into)?, Some(pm_info), None::<()>, ); let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pm_types) = enabled.payment_method_subtypes { for pm_type in pm_types { let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method_type)?; agg_nodes.push(( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } let any_aggregator_info = "Any aggregation for PaymentMethodsType"; let pm_type_agg_id = builder .make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let all_aggregator_info = "All aggregation for PaymentMethod"; let enabled_pm_agg_id = builder .make_all_aggregator( &[ (pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong), ( pm_type_agg_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some(all_aggregator_info), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; Some(enabled_pm_agg_id) } else { None }; Ok(agg_id) } #[cfg(feature = "v1")] fn compile_payment_method_enabled( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, enabled: admin_api::PaymentMethodsEnabled, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let agg_id = if !enabled .payment_method_types .as_ref() .map(|v| v.is_empty()) .unwrap_or(true) { let pm_info = "PaymentMethod"; let pm_id = builder.make_value_node( enabled.payment_method.into_dir_value().map(Into::into)?, Some(pm_info), None::<()>, ); let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pm_types) = enabled.payment_method_types { for pm_type in pm_types { let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method)?; agg_nodes.push(( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } let any_aggregator_info = "Any aggregation for PaymentMethodsType"; let pm_type_agg_id = builder .make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let all_aggregator_info = "All aggregation for PaymentMethod"; let enabled_pm_agg_id = builder .make_all_aggregator( &[ (pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong), ( pm_type_agg_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some(all_aggregator_info), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; Some(enabled_pm_agg_id) } else { None }; Ok(agg_id) } macro_rules! collect_global_variants { ($parent_enum:ident) => { &mut dir::enums::$parent_enum::iter() .map(dir::DirValue::$parent_enum) .collect::<Vec<_>>() }; } // #[cfg(feature = "v1")] fn global_vec_pmt( enabled_pmt: Vec<dir::DirValue>, builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, ) -> Vec<cgraph::NodeId> { let mut global_vector: Vec<dir::DirValue> = Vec::new(); global_vector.append(collect_global_variants!(PayLaterType)); global_vector.append(collect_global_variants!(WalletType)); global_vector.append(collect_global_variants!(BankRedirectType)); global_vector.append(collect_global_variants!(BankDebitType)); global_vector.append(collect_global_variants!(CryptoType)); global_vector.append(collect_global_variants!(RewardType)); global_vector.append(collect_global_variants!(RealTimePaymentType)); global_vector.append(collect_global_variants!(UpiType)); global_vector.append(collect_global_variants!(VoucherType)); global_vector.append(collect_global_variants!(GiftCardType)); global_vector.append(collect_global_variants!(BankTransferType)); global_vector.append(collect_global_variants!(CardRedirectType)); global_vector.append(collect_global_variants!(OpenBankingType)); global_vector.append(collect_global_variants!(MobilePaymentType)); global_vector.append(collect_global_variants!(NetworkTokenType)); global_vector.push(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); let global_vector = global_vector .into_iter() .filter(|global_value| !enabled_pmt.contains(global_value)) .collect::<Vec<_>>(); global_vector .into_iter() .map(|dir_v| { builder.make_value_node( cgraph::NodeValue::Value(dir_v), Some("Payment Method Type"), None::<()>, ) }) .collect::<Vec<_>>() } fn compile_graph_for_countries_and_currencies( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, config: &kgraph_types::CurrencyCountryFlowFilter, payment_method_type_node: cgraph::NodeId, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); agg_nodes.push(( payment_method_type_node, cgraph::Relation::Positive, cgraph::Strength::Normal, )); if let Some(country) = config.country.clone() { let node_country = country .into_iter() .map(|country| dir::DirValue::BillingCountry(api_enums::Country::from_alpha2(country))) .collect(); let country_agg = builder .make_in_aggregator(node_country, Some("Configs for Country"), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( country_agg, cgraph::Relation::Positive, cgraph::Strength::Weak, )) } if let Some(currency) = config.currency.clone() { let node_currency = currency .into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<Vec<_>, _>>()?; let currency_agg = builder .make_in_aggregator(node_currency, Some("Configs for Currency"), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( currency_agg, cgraph::Relation::Positive, cgraph::Strength::Normal, )) } if let Some(capture_method) = config .not_available_flows .and_then(|naf| naf.capture_method) { let make_capture_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(capture_method)), Some("Configs for CaptureMethod"), None::<()>, ); agg_nodes.push(( make_capture_node, cgraph::Relation::Negative, cgraph::Strength::Normal, )) } builder .make_all_aggregator( &agg_nodes, Some("Country & Currency Configs With Payment Method Type"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError) } // #[cfg(feature = "v1")] fn compile_config_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, config: &kgraph_types::CountryCurrencyFilter, connector: api_enums::RoutableConnectors,
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/kgraph_utils/benches/evaluation.rs
crates/kgraph_utils/benches/evaluation.rs
#![allow(unused, clippy::expect_used)] use std::{collections::HashMap, str::FromStr}; use api_models::{ admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, }; use common_utils::types::MinorUnit; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use euclid::{ dirval, dssa::graph::{self, CgraphExt}, frontend::dir, types::{NumValue, NumValueRefinement}, }; use hyperswitch_constraint_graph::{CycleCheck, Memoization}; use kgraph_utils::{error::KgraphError, transformers::IntoDirValue, types::CountryCurrencyFilter}; #[cfg(feature = "v1")] fn build_test_data( total_enabled: usize, total_pm_types: usize, ) -> hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let mut pms_enabled: Vec<PaymentMethodsEnabled> = Vec::new(); for _ in (0..total_enabled) { let mut pm_types: Vec<RequestPaymentMethodTypes> = Vec::new(); for _ in (0..total_pm_types) { pm_types.push(RequestPaymentMethodTypes { payment_method_type: api_enums::PaymentMethodType::Credit, payment_experience: None, card_networks: Some(vec![ api_enums::CardNetwork::Visa, api_enums::CardNetwork::Mastercard, ]), accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ api_enums::Currency::USD, api_enums::Currency::INR, ])), accepted_countries: None, minimum_amount: Some(MinorUnit::new(10)), maximum_amount: Some(MinorUnit::new(1000)), recurring_enabled: Some(true), installment_payment_enabled: Some(true), }); } pms_enabled.push(PaymentMethodsEnabled { payment_method: api_enums::PaymentMethod::Card, payment_method_types: Some(pm_types), }); } let profile_id = common_utils::generate_profile_id_of_default_length(); // #[cfg(feature = "v2")] // let stripe_account = MerchantConnectorResponse { // connector_type: api_enums::ConnectorType::FizOperations, // connector_name: "stripe".to_string(), // id: common_utils::generate_merchant_connector_account_id_of_default_length(), // connector_account_details: masking::Secret::new(serde_json::json!({})), // disabled: None, // metadata: None, // payment_methods_enabled: Some(pms_enabled), // connector_label: Some("something".to_string()), // frm_configs: None, // connector_webhook_details: None, // profile_id, // applepay_verified_domains: None, // pm_auth_config: None, // status: api_enums::ConnectorStatus::Inactive, // additional_merchant_data: None, // connector_wallets_details: None, // }; #[cfg(feature = "v1")] let stripe_account = MerchantConnectorResponse { connector_type: api_enums::ConnectorType::FizOperations, connector_name: "stripe".to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_account_details: masking::Secret::new(serde_json::json!({})), test_mode: None, disabled: None, metadata: None, payment_methods_enabled: Some(pms_enabled), business_country: Some(api_enums::CountryAlpha2::US), business_label: Some("hello".to_string()), connector_label: Some("something".to_string()), business_sub_label: Some("something".to_string()), frm_configs: None, connector_webhook_details: None, profile_id, applepay_verified_domains: None, pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, connector_wallets_details: None, }; let config = CountryCurrencyFilter { connector_configs: HashMap::new(), default_configs: None, }; #[cfg(feature = "v1")] kgraph_utils::mca::make_mca_graph(vec![stripe_account], &config) .expect("Failed graph construction") } #[cfg(feature = "v1")] fn evaluation(c: &mut Criterion) { let small_graph = build_test_data(3, 8); let big_graph = build_test_data(20, 20); c.bench_function("MCA Small Graph Evaluation", |b| { b.iter(|| { small_graph.key_value_analysis( dirval!(Connector = Stripe), &graph::AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = BWP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); }); }); c.bench_function("MCA Big Graph Evaluation", |b| { b.iter(|| { big_graph.key_value_analysis( dirval!(Connector = Stripe), &graph::AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = BWP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); }); }); } #[cfg(feature = "v1")] criterion_group!(benches, evaluation); #[cfg(feature = "v1")] criterion_main!(benches); #[cfg(feature = "v2")] fn main() {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_macros/src/lib.rs
crates/euclid_macros/src/lib.rs
mod inner; use proc_macro::TokenStream; #[proc_macro_derive(EnumNums)] pub fn enum_nums(ts: TokenStream) -> TokenStream { inner::enum_nums_inner(ts) } #[proc_macro] pub fn knowledge(ts: TokenStream) -> TokenStream { match inner::knowledge_inner(ts.into()) { Ok(ts) => ts.into(), Err(e) => e.into_compile_error().into(), } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_macros/src/inner.rs
crates/euclid_macros/src/inner.rs
mod enum_nums; mod knowledge; pub(crate) use enum_nums::enum_nums_inner; pub(crate) use knowledge::knowledge_inner;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_macros/src/inner/enum_nums.rs
crates/euclid_macros/src/inner/enum_nums.rs
use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; fn error() -> TokenStream2 { syn::Error::new( Span::call_site(), "'EnumNums' can only be derived on enums with unit variants".to_string(), ) .to_compile_error() } pub(crate) fn enum_nums_inner(ts: TokenStream) -> TokenStream { let derive_input = syn::parse_macro_input!(ts as syn::DeriveInput); let enum_obj = match derive_input.data { syn::Data::Enum(e) => e, _ => return error().into(), }; let enum_name = derive_input.ident; let mut match_arms = Vec::<TokenStream2>::with_capacity(enum_obj.variants.len()); for (i, variant) in enum_obj.variants.iter().enumerate() { match variant.fields { syn::Fields::Unit => {} _ => return error().into(), } let var_ident = &variant.ident; match_arms.push(quote! { Self::#var_ident => #i }); } let impl_block = quote! { impl #enum_name { pub fn to_num(&self) -> usize { match self { #(#match_arms),* } } } }; impl_block.into() }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_macros/src/inner/knowledge.rs
crates/euclid_macros/src/inner/knowledge.rs
use std::{ fmt::{Display, Formatter}, hash::Hash, rc::Rc, }; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use rustc_hash::{FxHashMap, FxHashSet}; use syn::{parse::Parse, Token}; mod strength { syn::custom_punctuation!(Normal, ->); syn::custom_punctuation!(Strong, ->>); } mod kw { syn::custom_keyword!(any); syn::custom_keyword!(not); } #[derive(Clone, PartialEq, Eq, Hash)] enum Comparison { LessThan, Equal, GreaterThan, GreaterThanEqual, LessThanEqual, } impl Display for Comparison { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let symbol = match self { Self::LessThan => "< ", Self::Equal => return Ok(()), Self::GreaterThanEqual => ">= ", Self::LessThanEqual => "<= ", Self::GreaterThan => "> ", }; write!(f, "{symbol}") } } impl Parse for Comparison { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { if input.peek(Token![>]) { input.parse::<Token![>]>()?; Ok(Self::GreaterThan) } else if input.peek(Token![<]) { input.parse::<Token![<]>()?; Ok(Self::LessThan) } else if input.peek(Token!(<=)) { input.parse::<Token![<=]>()?; Ok(Self::LessThanEqual) } else if input.peek(Token!(>=)) { input.parse::<Token![>=]>()?; Ok(Self::GreaterThanEqual) } else { Ok(Self::Equal) } } } #[derive(Clone, PartialEq, Eq, Hash)] enum ValueType { Any, EnumVariant(String), Number { number: i64, comparison: Comparison }, } impl ValueType { fn to_string(&self, key: &str) -> String { match self { Self::Any => format!("{key}(any)"), Self::EnumVariant(s) => format!("{key}({s})"), Self::Number { number, comparison } => { format!("{key}({comparison}{number})") } } } } impl Parse for ValueType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(syn::Ident) { let ident: syn::Ident = input.parse()?; Ok(Self::EnumVariant(ident.to_string())) } else if lookahead.peek(Token![>]) || lookahead.peek(Token![<]) || lookahead.peek(syn::LitInt) { let comparison: Comparison = input.parse()?; let number: syn::LitInt = input.parse()?; let num_val = number.base10_parse::<i64>()?; Ok(Self::Number { number: num_val, comparison, }) } else { Err(lookahead.error()) } } } #[derive(Clone, PartialEq, Eq, Hash)] struct Atom { key: String, value: ValueType, } impl Display for Atom { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.value.to_string(&self.key)) } } impl Parse for Atom { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let maybe_any: syn::Ident = input.parse()?; if maybe_any == "any" { let actual_key: syn::Ident = input.parse()?; Ok(Self { key: actual_key.to_string(), value: ValueType::Any, }) } else { let content; syn::parenthesized!(content in input); let value: ValueType = content.parse()?; Ok(Self { key: maybe_any.to_string(), value, }) } } } #[derive(Clone, PartialEq, Eq, Hash, strum::Display)] enum Strength { Normal, Strong, } impl Parse for Strength { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(strength::Strong) { input.parse::<strength::Strong>()?; Ok(Self::Strong) } else if lookahead.peek(strength::Normal) { input.parse::<strength::Normal>()?; Ok(Self::Normal) } else { Err(lookahead.error()) } } } #[derive(Clone, PartialEq, Eq, Hash, strum::Display)] enum Relation { Positive, Negative, } enum AtomType { Value { relation: Relation, atom: Rc<Atom>, }, InAggregator { key: String, values: Vec<String>, relation: Relation, }, } fn parse_atom_type_inner( input: syn::parse::ParseStream<'_>, key: syn::Ident, relation: Relation, ) -> syn::Result<AtomType> { let result = if input.peek(Token![in]) { input.parse::<Token![in]>()?; let bracketed; syn::bracketed!(bracketed in input); let mut values = Vec::<String>::new(); let first: syn::Ident = bracketed.parse()?; values.push(first.to_string()); while !bracketed.is_empty() { bracketed.parse::<Token![,]>()?; let next: syn::Ident = bracketed.parse()?; values.push(next.to_string()); } AtomType::InAggregator { key: key.to_string(), values, relation, } } else if input.peek(kw::any) { input.parse::<kw::any>()?; AtomType::Value { relation, atom: Rc::new(Atom { key: key.to_string(), value: ValueType::Any, }), } } else { let value: ValueType = input.parse()?; AtomType::Value { relation, atom: Rc::new(Atom { key: key.to_string(), value, }), } }; Ok(result) } impl Parse for AtomType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let key: syn::Ident = input.parse()?; let content; syn::parenthesized!(content in input); let relation = if content.peek(kw::not) { content.parse::<kw::not>()?; Relation::Negative } else { Relation::Positive }; let result = parse_atom_type_inner(&content, key, relation)?; if !content.is_empty() { Err(content.error("Unexpected input received after atom value")) } else { Ok(result) } } } fn parse_rhs_atom(input: syn::parse::ParseStream<'_>) -> syn::Result<Atom> { let key: syn::Ident = input.parse()?; let content; syn::parenthesized!(content in input); let lookahead = content.lookahead1(); let value_type = if lookahead.peek(kw::any) { content.parse::<kw::any>()?; ValueType::Any } else if lookahead.peek(syn::Ident) { let variant = content.parse::<syn::Ident>()?; ValueType::EnumVariant(variant.to_string()) } else { return Err(lookahead.error()); }; if !content.is_empty() { Err(content.error("Unexpected input received after atom value")) } else { Ok(Atom { key: key.to_string(), value: value_type, }) } } struct Rule { lhs: Vec<AtomType>, strength: Strength, rhs: Rc<Atom>, } impl Parse for Rule { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let first_atom: AtomType = input.parse()?; let mut lhs: Vec<AtomType> = vec![first_atom]; while input.peek(Token![&]) { input.parse::<Token![&]>()?; let and_atom: AtomType = input.parse()?; lhs.push(and_atom); } let strength: Strength = input.parse()?; let rhs: Rc<Atom> = Rc::new(parse_rhs_atom(input)?); input.parse::<Token![;]>()?; Ok(Self { lhs, strength, rhs }) } } #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, } impl Parse for Program { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let mut rules: Vec<Rc<Rule>> = Vec::new(); while !input.is_empty() { rules.push(Rc::new(input.parse::<Rule>()?)); } Ok(Self { rules }) } } struct GenContext { next_idx: usize, next_node_idx: usize, idx2atom: FxHashMap<usize, Rc<Atom>>, atom2idx: FxHashMap<Rc<Atom>, usize>, edges: FxHashMap<usize, FxHashSet<usize>>, compiled_atoms: FxHashMap<Rc<Atom>, proc_macro2::Ident>, } impl GenContext { fn new() -> Self { Self { next_idx: 1, next_node_idx: 1, idx2atom: FxHashMap::default(), atom2idx: FxHashMap::default(), edges: FxHashMap::default(), compiled_atoms: FxHashMap::default(), } } fn register_node(&mut self, atom: Rc<Atom>) -> usize { if let Some(idx) = self.atom2idx.get(&atom) { *idx } else { let this_idx = self.next_idx; self.next_idx += 1; self.idx2atom.insert(this_idx, Rc::clone(&atom)); self.atom2idx.insert(atom, this_idx); this_idx } } fn register_edge(&mut self, from: usize, to: usize) -> Result<(), String> { let node_children = self.edges.entry(from).or_default(); if node_children.contains(&to) { Err("Duplicate edge detected".to_string()) } else { node_children.insert(to); self.edges.entry(to).or_default(); Ok(()) } } fn register_rule(&mut self, rule: &Rule) -> Result<(), String> { let to_idx = self.register_node(Rc::clone(&rule.rhs)); for atom_type in &rule.lhs { if let AtomType::Value { atom, .. } = atom_type { let from_idx = self.register_node(Rc::clone(atom)); self.register_edge(from_idx, to_idx)?; } } Ok(()) } fn cycle_dfs( &self, node_id: usize, explored: &mut FxHashSet<usize>, visited: &mut FxHashSet<usize>, order: &mut Vec<usize>, ) -> Result<Option<Vec<usize>>, String> { if explored.contains(&node_id) { let position = order .iter() .position(|v| *v == node_id) .ok_or_else(|| "Error deciding cycle order".to_string())?; let cycle_order = order .get(position..) .ok_or_else(|| "Error getting cycle order".to_string())? .to_vec(); Ok(Some(cycle_order)) } else if visited.contains(&node_id) { Ok(None) } else { visited.insert(node_id); explored.insert(node_id); order.push(node_id); let dests = self .edges .get(&node_id) .ok_or_else(|| "Error getting edges of node".to_string())?; for dest in dests.iter().copied() { if let Some(cycle) = self.cycle_dfs(dest, explored, visited, order)? { return Ok(Some(cycle)); } } order.pop(); Ok(None) } } fn detect_graph_cycles(&self) -> Result<(), String> { let start_nodes = self.edges.keys().copied().collect::<Vec<usize>>(); let mut total_visited = FxHashSet::<usize>::default(); for node_id in start_nodes.iter().copied() { let mut explored = FxHashSet::<usize>::default(); let mut order = Vec::<usize>::new(); match self.cycle_dfs(node_id, &mut explored, &mut total_visited, &mut order)? { None => {} Some(order) => { let mut display_strings = Vec::<String>::with_capacity(order.len() + 1); for cycle_node_id in order { let node = self.idx2atom.get(&cycle_node_id).ok_or_else(|| { "Failed to find node during cycle display creation".to_string() })?; display_strings.push(node.to_string()); } let first = display_strings .first() .cloned() .ok_or("Unable to fill cycle display array")?; display_strings.push(first); return Err(format!("Found cycle: {}", display_strings.join(" -> "))); } } } Ok(()) } fn next_node_ident(&mut self) -> (proc_macro2::Ident, usize) { let this_idx = self.next_node_idx; self.next_node_idx += 1; (format_ident!("_node_{this_idx}"), this_idx) } fn compile_atom( &mut self, atom: &Rc<Atom>, tokens: &mut TokenStream, ) -> Result<proc_macro2::Ident, String> { let maybe_ident = self.compiled_atoms.get(atom); if let Some(ident) = maybe_ident { Ok(ident.clone()) } else { let (identifier, _) = self.next_node_ident(); let key = format_ident!("{}", &atom.key); let the_value = match &atom.value { ValueType::Any => quote! { cgraph::NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) }, ValueType::EnumVariant(variant) => { let variant = format_ident!("{}", variant); quote! { cgraph::NodeValue::Value(DirValue::#key(#key::#variant)) } } ValueType::Number { number, comparison } => { let comp_type = match comparison { Comparison::Equal => quote! { None }, Comparison::LessThan => quote! { Some(NumValueRefinement::LessThan) }, Comparison::GreaterThan => quote! { Some(NumValueRefinement::GreaterThan) }, Comparison::GreaterThanEqual => quote! { Some(NumValueRefinement::GreaterThanEqual) }, Comparison::LessThanEqual => quote! { Some(NumValueRefinement::LessThanEqual) }, }; quote! { cgraph::NodeValue::Value(DirValue::#key(NumValue { number: #number, refinement: #comp_type, })) } } }; let compiled = quote! { let #identifier = graph.make_value_node(#the_value, None, None::<()>); }; tokens.extend(compiled); self.compiled_atoms .insert(Rc::clone(atom), identifier.clone()); Ok(identifier) } } fn compile_atom_type( &mut self, atom_type: &AtomType, tokens: &mut TokenStream, ) -> Result<(proc_macro2::Ident, Relation), String> { match atom_type { AtomType::Value { relation, atom } => { let node_ident = self.compile_atom(atom, tokens)?; Ok((node_ident, relation.clone())) } AtomType::InAggregator { key, values, relation, } => { let key_ident = format_ident!("{key}"); let mut values_tokens: Vec<TokenStream> = Vec::new(); for value in values { let value_ident = format_ident!("{value}"); values_tokens.push(quote! { DirValue::#key_ident(#key_ident::#value_ident) }); } let (node_ident, _) = self.next_node_ident(); let node_code = quote! { let #node_ident = graph.make_in_aggregator( Vec::from_iter([#(#values_tokens),*]), None, None::<()>, ).expect("Failed to make In aggregator"); }; tokens.extend(node_code); Ok((node_ident, relation.clone())) } } } fn compile_rule(&mut self, rule: &Rule, tokens: &mut TokenStream) -> Result<(), String> { let rhs_ident = self.compile_atom(&rule.rhs, tokens)?; let mut node_details: Vec<(proc_macro2::Ident, Relation)> = Vec::with_capacity(rule.lhs.len()); for lhs_atom_type in &rule.lhs { let details = self.compile_atom_type(lhs_atom_type, tokens)?; node_details.push(details); } if node_details.len() <= 1 { let strength = format_ident!("{}", rule.strength.to_string()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); tokens.extend(quote! { graph.make_edge(#from_node, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::#relation, None::<cgraph::DomainId>) .expect("Failed to make edge"); }); } } else { let mut all_agg_nodes: Vec<TokenStream> = Vec::with_capacity(node_details.len()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); all_agg_nodes.push( quote! { (#from_node, cgraph::Relation::#relation, cgraph::Strength::Strong) }, ); } let strength = format_ident!("{}", rule.strength.to_string()); let (agg_node_ident, _) = self.next_node_ident(); tokens.extend(quote! { let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, None) .expect("Failed to make all aggregator node"); graph.make_edge(#agg_node_ident, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::Positive, None::<cgraph::DomainId>) .expect("Failed to create all aggregator edge"); }); } Ok(()) } fn compile(&mut self, program: Program) -> Result<TokenStream, String> { let mut tokens = TokenStream::new(); for rule in &program.rules { self.compile_rule(rule, &mut tokens)?; } let compiled = quote! {{ use euclid_graph_prelude::*; let mut graph = cgraph::ConstraintGraphBuilder::new(); #tokens graph.build() }}; Ok(compiled) } } pub(crate) fn knowledge_inner(ts: TokenStream) -> syn::Result<TokenStream> { let program = syn::parse::<Program>(ts.into())?; let mut gen_context = GenContext::new(); for rule in &program.rules { gen_context .register_rule(rule) .map_err(|msg| syn::Error::new(Span::call_site(), msg))?; } gen_context .detect_graph_cycles() .map_err(|msg| syn::Error::new(Span::call_site(), msg))?; gen_context .compile(program) .map_err(|msg| syn::Error::new(Span::call_site(), msg)) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_constraint_graph/src/builder.rs
crates/hyperswitch_constraint_graph/src/builder.rs
use std::sync::Arc; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ dense_map::DenseMap, error::GraphError, graph::ConstraintGraph, types::{ DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Metadata, Node, NodeId, NodeType, NodeValue, Relation, Strength, ValueNode, }, }; pub enum DomainIdOrIdentifier { DomainId(DomainId), DomainIdentifier(DomainIdentifier), } impl From<String> for DomainIdOrIdentifier { fn from(value: String) -> Self { Self::DomainIdentifier(DomainIdentifier::new(value)) } } impl From<DomainIdentifier> for DomainIdOrIdentifier { fn from(value: DomainIdentifier) -> Self { Self::DomainIdentifier(value) } } impl From<DomainId> for DomainIdOrIdentifier { fn from(value: DomainId) -> Self { Self::DomainId(value) } } #[derive(Debug)] pub struct ConstraintGraphBuilder<V: ValueNode> { domain: DenseMap<DomainId, DomainInfo>, nodes: DenseMap<NodeId, Node<V>>, edges: DenseMap<EdgeId, Edge>, domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>, value_map: FxHashMap<NodeValue<V>, NodeId>, edges_map: FxHashMap<(NodeId, NodeId, Option<DomainId>), EdgeId>, node_info: DenseMap<NodeId, Option<&'static str>>, node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, } #[allow(clippy::new_without_default)] impl<V> ConstraintGraphBuilder<V> where V: ValueNode, { pub fn new() -> Self { Self { domain: DenseMap::new(), nodes: DenseMap::new(), edges: DenseMap::new(), domain_identifier_map: FxHashMap::default(), value_map: FxHashMap::default(), edges_map: FxHashMap::default(), node_info: DenseMap::new(), node_metadata: DenseMap::new(), } } pub fn build(self) -> ConstraintGraph<V> { ConstraintGraph { domain: self.domain, domain_identifier_map: self.domain_identifier_map, nodes: self.nodes, edges: self.edges, value_map: self.value_map, node_info: self.node_info, node_metadata: self.node_metadata, } } fn retrieve_domain_from_identifier( &self, domain_ident: DomainIdentifier, ) -> Result<DomainId, GraphError<V>> { self.domain_identifier_map .get(&domain_ident) .copied() .ok_or(GraphError::DomainNotFound) } pub fn make_domain( &mut self, domain_identifier: String, domain_description: &str, ) -> Result<DomainId, GraphError<V>> { let domain_identifier = DomainIdentifier::new(domain_identifier); Ok(self .domain_identifier_map .clone() .get(&domain_identifier) .map_or_else( || { let domain_id = self.domain.push(DomainInfo { domain_identifier: domain_identifier.clone(), domain_description: domain_description.to_string(), }); self.domain_identifier_map .insert(domain_identifier, domain_id); domain_id }, |domain_id| *domain_id, )) } pub fn make_value_node<M: Metadata>( &mut self, value: NodeValue<V>, info: Option<&'static str>, metadata: Option<M>, ) -> NodeId { self.value_map.get(&value).copied().unwrap_or_else(|| { let node_id = self.nodes.push(Node::new(NodeType::Value(value.clone()))); let _node_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); self.value_map.insert(value, node_id); node_id }) } pub fn make_edge<T: Into<DomainIdOrIdentifier>>( &mut self, pred_id: NodeId, succ_id: NodeId, strength: Strength, relation: Relation, domain: Option<T>, ) -> Result<EdgeId, GraphError<V>> { self.ensure_node_exists(pred_id)?; self.ensure_node_exists(succ_id)?; let domain_id = domain .map(|d| match d.into() { DomainIdOrIdentifier::DomainIdentifier(ident) => { self.retrieve_domain_from_identifier(ident) } DomainIdOrIdentifier::DomainId(domain_id) => { self.ensure_domain_exists(domain_id).map(|_| domain_id) } }) .transpose()?; self.edges_map .get(&(pred_id, succ_id, domain_id)) .copied() .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge))) .map_or_else( || { let edge_id = self.edges.push(Edge { strength, relation, pred: pred_id, succ: succ_id, domain: domain_id, }); self.edges_map .insert((pred_id, succ_id, domain_id), edge_id); let pred = self .nodes .get_mut(pred_id) .ok_or(GraphError::NodeNotFound)?; pred.succs.push(edge_id); let succ = self .nodes .get_mut(succ_id) .ok_or(GraphError::NodeNotFound)?; succ.preds.push(edge_id); Ok(edge_id) }, |(edge_id, edge)| { if edge.strength == strength && edge.relation == relation { Ok(edge_id) } else { Err(GraphError::ConflictingEdgeCreated) } }, ) } pub fn make_all_aggregator<M: Metadata>( &mut self, nodes: &[(NodeId, Relation, Strength)], info: Option<&'static str>, metadata: Option<M>, domain_id: Option<DomainId>, ) -> Result<NodeId, GraphError<V>> { nodes .iter() .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; let aggregator_id = self.nodes.push(Node::new(NodeType::AllAggregator)); let _aggregator_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); for (node_id, relation, strength) in nodes { self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?; } Ok(aggregator_id) } pub fn make_any_aggregator<M: Metadata>( &mut self, nodes: &[(NodeId, Relation, Strength)], info: Option<&'static str>, metadata: Option<M>, domain_id: Option<DomainId>, ) -> Result<NodeId, GraphError<V>> { nodes .iter() .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; let aggregator_id = self.nodes.push(Node::new(NodeType::AnyAggregator)); let _aggregator_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); for (node_id, relation, strength) in nodes { self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?; } Ok(aggregator_id) } pub fn make_in_aggregator<M: Metadata>( &mut self, values: Vec<V>, info: Option<&'static str>, metadata: Option<M>, ) -> Result<NodeId, GraphError<V>> { let key = values .first() .ok_or(GraphError::NoInAggregatorValues)? .get_key(); for val in &values { if val.get_key() != key { Err(GraphError::MalformedGraph { reason: "Values for 'In' aggregator not of same key".to_string(), })?; } } let node_id = self .nodes .push(Node::new(NodeType::InAggregator(FxHashSet::from_iter( values, )))); let _aggregator_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); Ok(node_id) } fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError<V>> { if self.nodes.contains_key(id) { Ok(()) } else { Err(GraphError::NodeNotFound) } } fn ensure_domain_exists(&self, id: DomainId) -> Result<(), GraphError<V>> { if self.domain.contains_key(id) { Ok(()) } else { Err(GraphError::DomainNotFound) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_constraint_graph/src/lib.rs
crates/hyperswitch_constraint_graph/src/lib.rs
pub mod builder; mod dense_map; pub mod error; pub mod graph; pub mod types; pub use builder::ConstraintGraphBuilder; pub use error::{AnalysisTrace, GraphError}; pub use graph::ConstraintGraph; #[cfg(feature = "viz")] pub use types::NodeViz; pub use types::{ CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization, Node, NodeId, NodeValue, Relation, Strength, ValueNode, };
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_constraint_graph/src/dense_map.rs
crates/hyperswitch_constraint_graph/src/dense_map.rs
use std::{fmt, iter, marker::PhantomData, ops, slice, vec}; pub trait EntityId { fn get_id(&self) -> usize; fn with_id(id: usize) -> Self; } macro_rules! impl_entity { ($name:ident) => { impl $crate::dense_map::EntityId for $name { #[inline] fn get_id(&self) -> usize { self.0 } #[inline] fn with_id(id: usize) -> Self { Self(id) } } }; } pub(crate) use impl_entity; pub struct DenseMap<K, V> { data: Vec<V>, _marker: PhantomData<K>, } impl<K, V> DenseMap<K, V> { pub fn new() -> Self { Self { data: Vec::new(), _marker: PhantomData, } } } impl<K, V> Default for DenseMap<K, V> { fn default() -> Self { Self::new() } } impl<K, V> DenseMap<K, V> where K: EntityId, { pub fn push(&mut self, elem: V) -> K { let curr_len = self.data.len(); self.data.push(elem); K::with_id(curr_len) } #[inline] pub fn get(&self, idx: K) -> Option<&V> { self.data.get(idx.get_id()) } #[inline] pub fn get_mut(&mut self, idx: K) -> Option<&mut V> { self.data.get_mut(idx.get_id()) } #[inline] pub fn contains_key(&self, key: K) -> bool { key.get_id() < self.data.len() } #[inline] pub fn keys(&self) -> Keys<K> { Keys::new(0..self.data.len()) } #[inline] pub fn into_keys(self) -> Keys<K> { Keys::new(0..self.data.len()) } #[inline] pub fn values(&self) -> slice::Iter<'_, V> { self.data.iter() } #[inline] pub fn values_mut(&mut self) -> slice::IterMut<'_, V> { self.data.iter_mut() } #[inline] pub fn into_values(self) -> vec::IntoIter<V> { self.data.into_iter() } #[inline] pub fn iter(&self) -> Iter<'_, K, V> { Iter::new(self.data.iter()) } #[inline] pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { IterMut::new(self.data.iter_mut()) } } impl<K, V> fmt::Debug for DenseMap<K, V> where K: EntityId + fmt::Debug, V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map().entries(self.iter()).finish() } } pub struct Keys<K> { inner: ops::Range<usize>, _marker: PhantomData<K>, } impl<K> Keys<K> { fn new(range: ops::Range<usize>) -> Self { Self { inner: range, _marker: PhantomData, } } } impl<K> Iterator for Keys<K> where K: EntityId, { type Item = K; fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(K::with_id) } } pub struct Iter<'a, K, V> { inner: iter::Enumerate<slice::Iter<'a, V>>, _marker: PhantomData<K>, } impl<'a, K, V> Iter<'a, K, V> { fn new(iter: slice::Iter<'a, V>) -> Self { Self { inner: iter.enumerate(), _marker: PhantomData, } } } impl<'a, K, V> Iterator for Iter<'a, K, V> where K: EntityId, { type Item = (K, &'a V); fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(id, val)| (K::with_id(id), val)) } } pub struct IterMut<'a, K, V> { inner: iter::Enumerate<slice::IterMut<'a, V>>, _marker: PhantomData<K>, } impl<'a, K, V> IterMut<'a, K, V> { fn new(iter: slice::IterMut<'a, V>) -> Self { Self { inner: iter.enumerate(), _marker: PhantomData, } } } impl<'a, K, V> Iterator for IterMut<'a, K, V> where K: EntityId, { type Item = (K, &'a mut V); fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(id, val)| (K::with_id(id), val)) } } pub struct IntoIter<K, V> { inner: iter::Enumerate<vec::IntoIter<V>>, _marker: PhantomData<K>, } impl<K, V> IntoIter<K, V> { fn new(iter: vec::IntoIter<V>) -> Self { Self { inner: iter.enumerate(), _marker: PhantomData, } } } impl<K, V> Iterator for IntoIter<K, V> where K: EntityId, { type Item = (K, V); fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(id, val)| (K::with_id(id), val)) } } impl<K, V> IntoIterator for DenseMap<K, V> where K: EntityId, { type Item = (K, V); type IntoIter = IntoIter<K, V>; fn into_iter(self) -> Self::IntoIter { IntoIter::new(self.data.into_iter()) } } impl<K, V> FromIterator<V> for DenseMap<K, V> where K: EntityId, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = V>, { Self { data: Vec::from_iter(iter), _marker: PhantomData, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_constraint_graph/src/error.rs
crates/hyperswitch_constraint_graph/src/error.rs
use std::sync::{Arc, Weak}; use crate::types::{Metadata, NodeValue, Relation, RelationResolution, ValueNode}; #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "predecessor", rename_all = "snake_case")] pub enum ValueTracePredecessor<V: ValueNode> { Mandatory(Box<Weak<AnalysisTrace<V>>>), OneOf(Vec<Weak<AnalysisTrace<V>>>), } #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "trace", rename_all = "snake_case")] pub enum AnalysisTrace<V: ValueNode> { Value { value: NodeValue<V>, relation: Relation, predecessors: Option<ValueTracePredecessor<V>>, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, AllAggregation { unsatisfied: Vec<Weak<Self>>, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, AnyAggregation { unsatisfied: Vec<Weak<Self>>, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, InAggregation { expected: Vec<V>, found: Option<V>, relation: Relation, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, Contradiction { relation: RelationResolution, }, } #[derive(Debug, Clone, serde::Serialize, thiserror::Error)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum GraphError<V: ValueNode> { #[error("An edge was not found in the graph")] EdgeNotFound, #[error("Attempted to create a conflicting edge between two nodes")] ConflictingEdgeCreated, #[error("Cycle detected in graph")] CycleDetected, #[error("Domain wasn't found in the Graph")] DomainNotFound, #[error("Malformed Graph: {reason}")] MalformedGraph { reason: String }, #[error("A node was not found in the graph")] NodeNotFound, #[error("A value node was not found: {0:#?}")] ValueNodeNotFound(V), #[error("No values provided for an 'in' aggregator node")] NoInAggregatorValues, #[error("Error during analysis: {0:#?}")] AnalysisError(Weak<AnalysisTrace<V>>), } impl<V: ValueNode> GraphError<V> { pub fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace<V>>, Self> { match self { Self::AnalysisError(trace) => Ok(trace), _ => Err(self), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_constraint_graph/src/types.rs
crates/hyperswitch_constraint_graph/src/types.rs
use std::{ any::Any, fmt, hash, ops::{Deref, DerefMut}, sync::Arc, }; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{dense_map::impl_entity, error::AnalysisTrace}; pub trait KeyNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq {} pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq { type Key: KeyNode; fn get_key(&self) -> Self::Key; } #[cfg(feature = "viz")] pub trait NodeViz { fn viz(&self) -> String; } #[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)] #[serde(transparent)] pub struct NodeId(usize); impl_entity!(NodeId); #[derive(Debug)] pub struct Node<V: ValueNode> { pub node_type: NodeType<V>, pub preds: Vec<EdgeId>, pub succs: Vec<EdgeId>, } impl<V: ValueNode> Node<V> { pub(crate) fn new(node_type: NodeType<V>) -> Self { Self { node_type, preds: Vec::new(), succs: Vec::new(), } } } #[derive(Debug, PartialEq, Eq)] pub enum NodeType<V: ValueNode> { AllAggregator, AnyAggregator, InAggregator(FxHashSet<V>), Value(NodeValue<V>), } #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum NodeValue<V: ValueNode> { Key(<V as ValueNode>::Key), Value(V), } impl<V: ValueNode> From<V> for NodeValue<V> { fn from(value: V) -> Self { Self::Value(value) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct EdgeId(usize); impl_entity!(EdgeId); #[derive( Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash, strum::Display, PartialOrd, Ord, )] pub enum Strength { Weak, Normal, Strong, } impl Strength { pub fn get_resolved_strength(prev_strength: Self, curr_strength: Self) -> Self { std::cmp::max(prev_strength, curr_strength) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Relation { Positive, Negative, } impl From<Relation> for bool { fn from(value: Relation) -> Self { matches!(value, Relation::Positive) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] pub enum RelationResolution { Positive, Negative, Contradiction, } impl From<Relation> for RelationResolution { fn from(value: Relation) -> Self { match value { Relation::Positive => Self::Positive, Relation::Negative => Self::Negative, } } } impl RelationResolution { pub fn get_resolved_relation(prev_relation: Self, curr_relation: Self) -> Self { if prev_relation != curr_relation { Self::Contradiction } else { curr_relation } } } #[derive(Debug, Clone)] pub struct Edge { pub strength: Strength, pub relation: Relation, pub pred: NodeId, pub succ: NodeId, pub domain: Option<DomainId>, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct DomainId(usize); impl_entity!(DomainId); #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct DomainIdentifier(String); impl DomainIdentifier { pub fn new(identifier: String) -> Self { Self(identifier) } pub fn into_inner(&self) -> String { self.0.clone() } } impl From<String> for DomainIdentifier { fn from(value: String) -> Self { Self(value) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct DomainInfo { pub domain_identifier: DomainIdentifier, pub domain_description: String, } pub trait CheckingContext { type Value: ValueNode; fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self where L: Into<Self::Value>; fn check_presence(&self, value: &NodeValue<Self::Value>, strength: Strength) -> bool; fn get_values_by_key( &self, expected: &<Self::Value as ValueNode>::Key, ) -> Option<Vec<Self::Value>>; } #[derive(Debug, Clone, serde::Serialize)] pub struct Memoization<V: ValueNode>( #[allow(clippy::type_complexity)] FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>, ); impl<V: ValueNode> Memoization<V> { pub fn new() -> Self { Self(FxHashMap::default()) } } impl<V: ValueNode> Default for Memoization<V> { #[inline] fn default() -> Self { Self::new() } } impl<V: ValueNode> Deref for Memoization<V> { type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<V: ValueNode> DerefMut for Memoization<V> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(Debug, Clone)] pub struct CycleCheck(FxHashMap<NodeId, (Strength, RelationResolution)>); impl CycleCheck { pub fn new() -> Self { Self(FxHashMap::default()) } } impl Default for CycleCheck { #[inline] fn default() -> Self { Self::new() } } impl Deref for CycleCheck { type Target = FxHashMap<NodeId, (Strength, RelationResolution)>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for CycleCheck { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub trait Metadata: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} erased_serde::serialize_trait_object!(Metadata); impl<M> Metadata for M where M: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_constraint_graph/src/graph.rs
crates/hyperswitch_constraint_graph/src/graph.rs
use std::sync::{Arc, Weak}; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ builder, dense_map::DenseMap, error::{self, AnalysisTrace, GraphError}, types::{ CheckingContext, CycleCheck, DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Memoization, Metadata, Node, NodeId, NodeType, NodeValue, Relation, RelationResolution, Strength, ValueNode, }, }; #[derive(Debug)] struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> { ctx: &'a C, node: &'a Node<V>, node_id: NodeId, relation: Relation, strength: Strength, memo: &'a mut Memoization<V>, cycle_map: &'a mut CycleCheck, domains: Option<&'a [DomainId]>, } #[derive(Debug)] pub struct ConstraintGraph<V: ValueNode> { pub domain: DenseMap<DomainId, DomainInfo>, pub domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>, pub nodes: DenseMap<NodeId, Node<V>>, pub edges: DenseMap<EdgeId, Edge>, pub value_map: FxHashMap<NodeValue<V>, NodeId>, pub node_info: DenseMap<NodeId, Option<&'static str>>, pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, } impl<V> ConstraintGraph<V> where V: ValueNode, { fn get_predecessor_edges_by_domain( &self, node_id: NodeId, domains: Option<&[DomainId]>, ) -> Result<Vec<&Edge>, GraphError<V>> { let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; let mut final_list = Vec::new(); for &pred in &node.preds { let edge = self.edges.get(pred).ok_or(GraphError::EdgeNotFound)?; if let Some((domain_id, domains)) = edge.domain.zip(domains) { if domains.contains(&domain_id) { final_list.push(edge); } } else if edge.domain.is_none() { final_list.push(edge); } } Ok(final_list) } #[allow(clippy::too_many_arguments)] pub fn check_node<C>( &self, ctx: &C, node_id: NodeId, relation: Relation, strength: Strength, memo: &mut Memoization<V>, cycle_map: &mut CycleCheck, domains: Option<&[String]>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let domains = domains .map(|domain_idents| { domain_idents .iter() .map(|domain_ident| { self.domain_identifier_map .get(&DomainIdentifier::new(domain_ident.to_string())) .copied() .ok_or(GraphError::DomainNotFound) }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; self.check_node_inner( ctx, node_id, relation, strength, memo, cycle_map, domains.as_deref(), ) } #[allow(clippy::too_many_arguments)] pub fn check_node_inner<C>( &self, ctx: &C, node_id: NodeId, relation: Relation, strength: Strength, memo: &mut Memoization<V>, cycle_map: &mut CycleCheck, domains: Option<&[DomainId]>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; if let Some(already_memo) = memo.get(&(node_id, relation, strength)) { already_memo .clone() .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).copied() { let strength_relation = Strength::get_resolved_strength(initial_strength, strength); let relation_resolve = RelationResolution::get_resolved_relation(initial_relation, relation.into()); cycle_map.entry(node_id).and_modify(|value| { value.0 = strength_relation; value.1 = relation_resolve }); Ok(()) } else { let check_node_context = CheckNodeContext { node, node_id, relation, strength, memo, cycle_map, ctx, domains, }; match &node.node_type { NodeType::AllAggregator => self.validate_all_aggregator(check_node_context), NodeType::AnyAggregator => self.validate_any_aggregator(check_node_context), NodeType::InAggregator(expected) => { self.validate_in_aggregator(check_node_context, expected) } NodeType::Value(val) => self.validate_value_node(check_node_context, val), } } } fn validate_all_aggregator<C>( &self, vald: CheckNodeContext<'_, V, C>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { vald.cycle_map .insert(vald.node_id, (vald.strength, vald.relation.into())); if let Err(e) = self.check_node_inner( vald.ctx, edge.pred, edge.relation, edge.strength, vald.memo, vald.cycle_map, vald.domains, ) { unsatisfied.push(e.get_analysis_trace()?); } if let Some((_resolved_strength, resolved_relation)) = vald.cycle_map.remove(&vald.node_id) { if resolved_relation == RelationResolution::Contradiction { let err = Arc::new(AnalysisTrace::Contradiction { relation: resolved_relation, }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); return Err(GraphError::AnalysisError(Arc::downgrade(&err))); } } } if !unsatisfied.is_empty() { let err = Arc::new(AnalysisTrace::AllAggregation { unsatisfied, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) } else { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } } fn validate_any_aggregator<C>( &self, vald: CheckNodeContext<'_, V, C>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); let mut matched_one = false; for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { vald.cycle_map .insert(vald.node_id, (vald.strength, vald.relation.into())); if let Err(e) = self.check_node_inner( vald.ctx, edge.pred, edge.relation, edge.strength, vald.memo, vald.cycle_map, vald.domains, ) { unsatisfied.push(e.get_analysis_trace()?); } else { matched_one = true; } if let Some((_resolved_strength, resolved_relation)) = vald.cycle_map.remove(&vald.node_id) { if resolved_relation == RelationResolution::Contradiction { let err = Arc::new(AnalysisTrace::Contradiction { relation: resolved_relation, }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); return Err(GraphError::AnalysisError(Arc::downgrade(&err))); } } } if matched_one || vald.node.preds.is_empty() { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } else { let err = Arc::new(AnalysisTrace::AnyAggregation { unsatisfied: unsatisfied.clone(), info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) } } fn validate_in_aggregator<C>( &self, vald: CheckNodeContext<'_, V, C>, expected: &FxHashSet<V>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let the_key = expected .iter() .next() .ok_or_else(|| GraphError::MalformedGraph { reason: "An OnlyIn aggregator node must have at least one expected value" .to_string(), })? .get_key(); let ctx_vals = if let Some(vals) = vald.ctx.get_values_by_key(&the_key) { vals } else { return if let Strength::Weak = vald.strength { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } else { let err = Arc::new(AnalysisTrace::InAggregation { expected: expected.iter().cloned().collect(), found: None, relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) }; }; let relation_bool: bool = vald.relation.into(); for ctx_value in ctx_vals { if expected.contains(&ctx_value) != relation_bool { let err = Arc::new(AnalysisTrace::InAggregation { expected: expected.iter().cloned().collect(), found: Some(ctx_value.clone()), relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; } } vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } fn validate_value_node<C>( &self, vald: CheckNodeContext<'_, V, C>, val: &NodeValue<V>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let mut errors = Vec::<Weak<AnalysisTrace<V>>>::new(); let mut matched_one = false; self.context_analysis( vald.node_id, vald.relation, vald.strength, vald.ctx, val, vald.memo, )?; for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { vald.cycle_map .insert(vald.node_id, (vald.strength, vald.relation.into())); let result = self.check_node_inner( vald.ctx, edge.pred, edge.relation, edge.strength, vald.memo, vald.cycle_map, vald.domains, ); if let Some((resolved_strength, resolved_relation)) = vald.cycle_map.remove(&vald.node_id) { if resolved_relation == RelationResolution::Contradiction { let err = Arc::new(AnalysisTrace::Contradiction { relation: resolved_relation, }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); return Err(GraphError::AnalysisError(Arc::downgrade(&err))); } else if resolved_strength != vald.strength { self.context_analysis( vald.node_id, vald.relation, resolved_strength, vald.ctx, val, vald.memo, )? } } match (edge.strength, result) { (Strength::Strong, Err(trace)) => { let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new( trace.get_analysis_trace()?, ))), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; } (Strength::Strong, Ok(_)) => { matched_one = true; } (Strength::Normal | Strength::Weak, Err(trace)) => { errors.push(trace.get_analysis_trace()?); } (Strength::Normal | Strength::Weak, Ok(_)) => { matched_one = true; } } } if matched_one || vald.node.preds.is_empty() { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } else { let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) } } fn context_analysis<C>( &self, node_id: NodeId, relation: Relation, strength: Strength, ctx: &C, val: &NodeValue<V>, memo: &mut Memoization<V>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let in_context = ctx.check_presence(val, strength); let relation_bool: bool = relation.into(); if in_context != relation_bool { let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation, predecessors: None, info: self.node_info.get(node_id).copied().flatten(), metadata: self.node_metadata.get(node_id).cloned().flatten(), }); memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; } if !relation_bool { memo.insert((node_id, relation, strength), Ok(())); return Ok(()); } Ok(()) } pub fn combine(g1: &Self, g2: &Self) -> Result<Self, GraphError<V>> { let mut node_builder = builder::ConstraintGraphBuilder::new(); let mut g1_old2new_id = DenseMap::<NodeId, NodeId>::new(); let mut g2_old2new_id = DenseMap::<NodeId, NodeId>::new(); let mut g1_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); let mut g2_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); let add_domain = |node_builder: &mut builder::ConstraintGraphBuilder<V>, domain: DomainInfo| -> Result<DomainId, GraphError<V>> { node_builder.make_domain( domain.domain_identifier.into_inner(), &domain.domain_description, ) }; let add_node = |node_builder: &mut builder::ConstraintGraphBuilder<V>, node: &Node<V>| -> Result<NodeId, GraphError<V>> { match &node.node_type { NodeType::Value(node_value) => { Ok(node_builder.make_value_node(node_value.clone(), None, None::<()>)) } NodeType::AllAggregator => { Ok(node_builder.make_all_aggregator(&[], None, None::<()>, None)?) } NodeType::AnyAggregator => { Ok(node_builder.make_any_aggregator(&[], None, None::<()>, None)?) } NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator( expected.iter().cloned().collect(), None, None::<()>, )?), } }; for (_old_domain_id, domain) in g1.domain.iter() { let new_domain_id = add_domain(&mut node_builder, domain.clone())?; g1_old2new_domain_id.push(new_domain_id); } for (_old_domain_id, domain) in g2.domain.iter() { let new_domain_id = add_domain(&mut node_builder, domain.clone())?; g2_old2new_domain_id.push(new_domain_id); } for (_old_node_id, node) in g1.nodes.iter() { let new_node_id = add_node(&mut node_builder, node)?; g1_old2new_id.push(new_node_id); } for (_old_node_id, node) in g2.nodes.iter() { let new_node_id = add_node(&mut node_builder, node)?; g2_old2new_id.push(new_node_id); } for edge in g1.edges.values() { let new_pred_id = g1_old2new_id .get(edge.pred) .ok_or(GraphError::NodeNotFound)?; let new_succ_id = g1_old2new_id .get(edge.succ) .ok_or(GraphError::NodeNotFound)?; let domain_ident = edge .domain .map(|domain_id| g1.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) .transpose()? .map(|domain| domain.domain_identifier.clone()); node_builder.make_edge( *new_pred_id, *new_succ_id, edge.strength, edge.relation, domain_ident, )?; } for edge in g2.edges.values() { let new_pred_id = g2_old2new_id .get(edge.pred) .ok_or(GraphError::NodeNotFound)?; let new_succ_id = g2_old2new_id .get(edge.succ) .ok_or(GraphError::NodeNotFound)?; let domain_ident = edge .domain .map(|domain_id| g2.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) .transpose()? .map(|domain| domain.domain_identifier.clone()); node_builder.make_edge( *new_pred_id, *new_succ_id, edge.strength, edge.relation, domain_ident, )?; } Ok(node_builder.build()) } } #[cfg(feature = "viz")] mod viz { use graphviz_rust::{ dot_generator::*, dot_structures::*, printer::{DotPrinter, PrinterContext}, }; use crate::{dense_map::EntityId, types, ConstraintGraph, NodeViz, ValueNode}; fn get_node_id(node_id: types::NodeId) -> String { format!("N{}", node_id.get_id()) } impl<V> ConstraintGraph<V> where V: ValueNode + NodeViz, <V as ValueNode>::Key: NodeViz, { fn get_node_label(node: &types::Node<V>) -> String { let label = match &node.node_type { types::NodeType::Value(types::NodeValue::Key(key)) => format!("any {}", key.viz()), types::NodeType::Value(types::NodeValue::Value(val)) => { format!("{} = {}", val.get_key().viz(), val.viz()) } types::NodeType::AllAggregator => "&&".to_string(), types::NodeType::AnyAggregator => "| |".to_string(), types::NodeType::InAggregator(agg) => { let key = if let Some(val) = agg.iter().next() { val.get_key().viz() } else { return "empty in".to_string(); }; let nodes = agg.iter().map(NodeViz::viz).collect::<Vec<_>>(); format!("{key} in [{}]", nodes.join(", ")) } }; format!("\"{label}\"") } fn build_node(cg_node_id: types::NodeId, cg_node: &types::Node<V>) -> Node { let viz_node_id = get_node_id(cg_node_id); let viz_node_label = Self::get_node_label(cg_node); node!(viz_node_id; attr!("label", viz_node_label)) } fn build_edge(cg_edge: &types::Edge) -> Edge { let pred_vertex = get_node_id(cg_edge.pred); let succ_vertex = get_node_id(cg_edge.succ); let arrowhead = match cg_edge.strength { types::Strength::Weak => "onormal", types::Strength::Normal => "normal", types::Strength::Strong => "normalnormal", }; let color = match cg_edge.relation { types::Relation::Positive => "blue", types::Relation::Negative => "red", }; edge!( node_id!(pred_vertex) => node_id!(succ_vertex); attr!("arrowhead", arrowhead), attr!("color", color) ) } pub fn get_viz_digraph(&self) -> Graph { graph!( strict di id!("constraint_graph"), self.nodes .iter() .map(|(node_id, node)| Self::build_node(node_id, node)) .map(Stmt::Node) .chain(self.edges.values().map(Self::build_edge).map(Stmt::Edge)) .collect::<Vec<_>>() ) } pub fn get_viz_digraph_string(&self) -> String { let mut ctx = PrinterContext::default(); let digraph = self.get_viz_digraph(); digraph.print(&mut ctx) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/redis_interface/src/errors.rs
crates/redis_interface/src/errors.rs
//! Errors specific to this custom redis interface #[derive(Debug, thiserror::Error, PartialEq)] pub enum RedisError { #[error("Invalid Redis configuration: {0}")] InvalidConfiguration(String), #[error("Failed to set key value in Redis")] SetFailed, #[error("Failed to set key value in Redis. Duplicate value")] SetNxFailed, #[error("Failed to set key value with expiry in Redis")] SetExFailed, #[error("Failed to set expiry for key value in Redis")] SetExpiryFailed, #[error("Failed to get key value in Redis")] GetFailed, #[error("Failed to delete key value in Redis")] DeleteFailed, #[error("Failed to append entry to Redis stream")] StreamAppendFailed, #[error("Failed to read entries from Redis stream")] StreamReadFailed, #[error("Failed to get stream length")] GetLengthFailed, #[error("Failed to delete entries from Redis stream")] StreamDeleteFailed, #[error("Failed to trim entries from Redis stream")] StreamTrimFailed, #[error("Failed to acknowledge Redis stream entry")] StreamAcknowledgeFailed, #[error("Stream is either empty or not available")] StreamEmptyOrNotAvailable, #[error("Failed to create Redis consumer group")] ConsumerGroupCreateFailed, #[error("Failed to destroy Redis consumer group")] ConsumerGroupDestroyFailed, #[error("Failed to delete consumer from consumer group")] ConsumerGroupRemoveConsumerFailed, #[error("Failed to set last ID on consumer group")] ConsumerGroupSetIdFailed, #[error("Failed to set Redis stream message owner")] ConsumerGroupClaimFailed, #[error("Failed to serialize application type to JSON")] JsonSerializationFailed, #[error("Failed to deserialize application type from JSON")] JsonDeserializationFailed, #[error("Failed to set hash in Redis")] SetHashFailed, #[error("Failed to set hash field in Redis")] SetHashFieldFailed, #[error("Failed to add members to set in Redis")] SetAddMembersFailed, #[error("Failed to get hash field in Redis")] GetHashFieldFailed, #[error("The requested value was not found in Redis")] NotFound, #[error("Invalid RedisEntryId provided")] InvalidRedisEntryId, #[error("Failed to establish Redis connection")] RedisConnectionError, #[error("Failed to subscribe to a channel")] SubscribeError, #[error("Failed to publish to a channel")] PublishError, #[error("Failed while receiving message from publisher")] OnMessageError, #[error("Got an unknown result from redis")] UnknownResult, #[error("Failed to append elements to list in Redis")] AppendElementsToListFailed, #[error("Failed to get list elements in Redis")] GetListElementsFailed, #[error("Failed to get length of list")] GetListLengthFailed, #[error("Failed to pop list elements in Redis")] PopListElementsFailed, #[error("Failed to increment hash field in Redis")] IncrementHashFieldFailed, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/redis_interface/src/lib.rs
crates/redis_interface/src/lib.rs
//! Intermediate module for encapsulate all the redis related functionality //! //! Provides structs to represent redis connection and all functions that redis provides and //! are used in the `router` crate. Abstractions for creating a new connection while also facilitating //! redis connection pool and configuration based types. //! //! # Examples //! ``` //! use redis_interface::{types::RedisSettings, RedisConnectionPool}; //! //! #[tokio::main] //! async fn main() { //! let redis_conn = RedisConnectionPool::new(&RedisSettings::default()).await; //! // ... redis_conn ready to use //! } //! ``` pub mod commands; pub mod errors; pub mod types; use std::sync::{atomic, Arc}; use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use fred::interfaces::PubsubInterface; use fred::{ clients::Transaction, interfaces::ClientLike, prelude::{EventInterface, TransactionInterface}, }; pub use self::types::*; pub struct RedisConnectionPool { pub pool: Arc<fred::prelude::RedisPool>, pub key_prefix: String, pub config: Arc<RedisConfig>, pub subscriber: Arc<SubscriberClient>, pub publisher: Arc<RedisClient>, pub is_redis_available: Arc<atomic::AtomicBool>, } pub struct RedisClient { inner: fred::prelude::RedisClient, } impl std::ops::Deref for RedisClient { type Target = fred::prelude::RedisClient; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisClient { pub async fn new( config: fred::types::RedisConfig, reconnect_policy: fred::types::ReconnectPolicy, perf: fred::types::PerformanceConfig, ) -> CustomResult<Self, errors::RedisError> { let client = fred::prelude::RedisClient::new(config, Some(perf), None, Some(reconnect_policy)); client.connect(); client .wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; Ok(Self { inner: client }) } } pub struct SubscriberClient { inner: fred::clients::SubscriberClient, pub is_subscriber_handler_spawned: Arc<atomic::AtomicBool>, } impl SubscriberClient { pub async fn new( config: fred::types::RedisConfig, reconnect_policy: fred::types::ReconnectPolicy, perf: fred::types::PerformanceConfig, ) -> CustomResult<Self, errors::RedisError> { let client = fred::clients::SubscriberClient::new(config, Some(perf), None, Some(reconnect_policy)); client.connect(); client .wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; Ok(Self { inner: client, is_subscriber_handler_spawned: Arc::new(atomic::AtomicBool::new(false)), }) } } impl std::ops::Deref for SubscriberClient { type Target = fred::clients::SubscriberClient; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisConnectionPool { /// Create a new Redis connection pub async fn new(conf: &RedisSettings) -> CustomResult<Self, errors::RedisError> { let redis_connection_url = match conf.cluster_enabled { // Fred relies on this format for specifying cluster where the host port is ignored & only query parameters are used for node addresses // redis-cluster://username:password@host:port?node=bar.com:30002&node=baz.com:30003 true => format!( "redis-cluster://{}:{}?{}", conf.host, conf.port, conf.cluster_urls .iter() .flat_map(|url| vec!["&", url]) .skip(1) .collect::<String>() ), false => format!( "redis://{}:{}", //URI Schema conf.host, conf.port, ), }; let mut config = fred::types::RedisConfig::from_url(&redis_connection_url) .change_context(errors::RedisError::RedisConnectionError)?; let perf = fred::types::PerformanceConfig { auto_pipeline: conf.auto_pipeline, default_command_timeout: std::time::Duration::from_secs(conf.default_command_timeout), max_feed_count: conf.max_feed_count, backpressure: fred::types::BackpressureConfig { disable_auto_backpressure: conf.disable_auto_backpressure, max_in_flight_commands: conf.max_in_flight_commands, policy: fred::types::BackpressurePolicy::Drain, }, }; let connection_config = fred::types::ConnectionConfig { unresponsive_timeout: std::time::Duration::from_secs(conf.unresponsive_timeout), ..fred::types::ConnectionConfig::default() }; if !conf.use_legacy_version { config.version = fred::types::RespVersion::RESP3; } config.tracing = fred::types::TracingConfig::new(true); config.blocking = fred::types::Blocking::Error; let reconnect_policy = fred::types::ReconnectPolicy::new_constant( conf.reconnect_max_attempts, conf.reconnect_delay, ); let subscriber = SubscriberClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?; let publisher = RedisClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?; let pool = fred::prelude::RedisPool::new( config, Some(perf), Some(connection_config), Some(reconnect_policy), conf.pool_size, ) .change_context(errors::RedisError::RedisConnectionError)?; pool.connect(); pool.wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; let config = RedisConfig::from(conf); Ok(Self { pool: Arc::new(pool), config: Arc::new(config), is_redis_available: Arc::new(atomic::AtomicBool::new(true)), subscriber: Arc::new(subscriber), publisher: Arc::new(publisher), key_prefix: String::default(), }) } pub fn clone(&self, key_prefix: &str) -> Self { Self { pool: Arc::clone(&self.pool), key_prefix: key_prefix.to_string(), config: Arc::clone(&self.config), subscriber: Arc::clone(&self.subscriber), publisher: Arc::clone(&self.publisher), is_redis_available: Arc::clone(&self.is_redis_available), } } pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) { use futures::StreamExt; use tokio_stream::wrappers::BroadcastStream; let error_rxs: Vec<BroadcastStream<fred::error::RedisError>> = self .pool .clients() .iter() .map(|client| BroadcastStream::new(client.error_rx())) .collect(); let mut error_rx = futures::stream::select_all(error_rxs); loop { if let Some(Ok(error)) = error_rx.next().await { tracing::error!(?error, "Redis protocol or connection error"); if self.pool.state() == fred::types::ClientState::Disconnected { if tx.send(()).is_err() { tracing::error!("The redis shutdown signal sender failed to signal"); } self.is_redis_available .store(false, atomic::Ordering::SeqCst); break; } } } } pub async fn on_unresponsive(&self) { let _ = self.pool.clients().iter().map(|client| { client.on_unresponsive(|server| { tracing::warn!(redis_server =?server.host, "Redis server is unresponsive"); Ok(()) }) }); } pub fn get_transaction(&self) -> Transaction { self.pool.next().multi() } } pub struct RedisConfig { default_ttl: u32, default_stream_read_count: u64, default_hash_ttl: u32, cluster_enabled: bool, } impl From<&RedisSettings> for RedisConfig { fn from(config: &RedisSettings) -> Self { Self { default_ttl: config.default_ttl, default_stream_read_count: config.stream_read_count, default_hash_ttl: config.default_hash_ttl, cluster_enabled: config.cluster_enabled, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_redis_error() { let x = errors::RedisError::ConsumerGroupClaimFailed.to_string(); assert_eq!(x, "Failed to set Redis stream message owner".to_string()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/redis_interface/src/types.rs
crates/redis_interface/src/types.rs
//! Data types and type conversions //! from `fred`'s internal data-types to custom data-types use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; use crate::{errors, RedisConnectionPool}; pub struct RedisValue { inner: FredRedisValue, } impl std::ops::Deref for RedisValue { type Target = FredRedisValue; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisValue { pub fn new(value: FredRedisValue) -> Self { Self { inner: value } } pub fn into_inner(self) -> FredRedisValue { self.inner } pub fn from_bytes(val: Vec<u8>) -> Self { Self { inner: FredRedisValue::Bytes(val.into()), } } pub fn from_string(value: String) -> Self { Self { inner: FredRedisValue::String(value.into()), } } } impl From<RedisValue> for FredRedisValue { fn from(v: RedisValue) -> Self { v.inner } } #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct RedisSettings { pub host: String, pub port: u16, pub cluster_enabled: bool, pub cluster_urls: Vec<String>, pub use_legacy_version: bool, pub pool_size: usize, pub reconnect_max_attempts: u32, /// Reconnect delay in milliseconds pub reconnect_delay: u32, /// TTL in seconds pub default_ttl: u32, /// TTL for hash-tables in seconds pub default_hash_ttl: u32, pub stream_read_count: u64, pub auto_pipeline: bool, pub disable_auto_backpressure: bool, pub max_in_flight_commands: u64, pub default_command_timeout: u64, pub max_feed_count: u64, pub unresponsive_timeout: u64, } impl RedisSettings { /// Validates the Redis configuration provided. pub fn validate(&self) -> CustomResult<(), errors::RedisError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; when(self.host.is_default_or_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `host` must be specified".into(), )) })?; when(self.cluster_enabled && self.cluster_urls.is_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), )) })?; when( self.default_command_timeout < self.unresponsive_timeout, || { Err(errors::RedisError::InvalidConfiguration( "Unresponsive timeout cannot be greater than the command timeout".into(), ) .into()) }, ) } } impl Default for RedisSettings { fn default() -> Self { Self { host: "127.0.0.1".to_string(), port: 6379, cluster_enabled: false, cluster_urls: vec![], use_legacy_version: false, pool_size: 5, reconnect_max_attempts: 5, reconnect_delay: 5, default_ttl: 300, stream_read_count: 1, default_hash_ttl: 900, auto_pipeline: true, disable_auto_backpressure: false, max_in_flight_commands: 5000, default_command_timeout: 30, max_feed_count: 200, unresponsive_timeout: 10, } } } #[derive(Debug)] pub enum RedisEntryId { UserSpecifiedID { milliseconds: String, sequence_number: String, }, AutoGeneratedID, AfterLastID, /// Applicable only with consumer groups UndeliveredEntryID, } impl From<RedisEntryId> for fred::types::XID { fn from(id: RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } impl From<&RedisEntryId> for fred::types::XID { fn from(id: &RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } #[derive(Eq, PartialEq)] pub enum SetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for SetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { // Returns String ( "OK" ) in case of success fred::types::RedisValue::String(_) => Ok(Self::KeySet), // Return Null in case of failure fred::types::RedisValue::Null => Ok(Self::KeyNotSet), // Unexpected behaviour _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected SETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum HsetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for HsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected HSETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum MsetnxReply { KeysSet, KeysNotSet, // At least one existing key } impl fred::types::FromRedis for MsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet), fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected MSETNX command reply", )), } } } #[derive(Debug)] pub enum StreamCapKind { MinID, MaxLen, } impl From<StreamCapKind> for fred::types::XCapKind { fn from(item: StreamCapKind) -> Self { match item { StreamCapKind::MaxLen => Self::MaxLen, StreamCapKind::MinID => Self::MinID, } } } #[derive(Debug)] pub enum StreamCapTrim { Exact, AlmostExact, } impl From<StreamCapTrim> for fred::types::XCapTrim { fn from(item: StreamCapTrim) -> Self { match item { StreamCapTrim::Exact => Self::Exact, StreamCapTrim::AlmostExact => Self::AlmostExact, } } } #[derive(Debug)] pub enum DelReply { KeyDeleted, KeyNotDeleted, // Key not found } impl DelReply { pub fn is_key_deleted(&self) -> bool { matches!(self, Self::KeyDeleted) } pub fn is_key_not_deleted(&self) -> bool { matches!(self, Self::KeyNotDeleted) } } impl fred::types::FromRedis for DelReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected del command reply", )), } } } #[derive(Debug)] pub enum SaddReply { KeySet, KeyNotSet, } impl fred::types::FromRedis for SaddReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected sadd command reply", )), } } } #[derive(Debug)] pub enum SetGetReply<T> { ValueSet(T), // Value was set and this is the value that was set ValueExists(T), // Value already existed and this is the existing value } impl<T> SetGetReply<T> { pub fn get_value(&self) -> &T { match self { Self::ValueSet(value) => value, Self::ValueExists(value) => value, } } } #[derive(Debug)] pub struct RedisKey(String); impl RedisKey { pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String { pool.add_prefix(&self.0) } pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String { self.0.clone() } } impl<T: AsRef<str>> From<T> for RedisKey { fn from(value: T) -> Self { let value = value.as_ref(); Self(value.to_string()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/redis_interface/src/commands.rs
crates/redis_interface/src/commands.rs
//! An interface to abstract the `fred` commands //! //! The folder provides generic functions for providing serialization //! and deserialization while calling redis. //! It also includes instruments to provide tracing. use std::fmt::Debug; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, ByteSliceExt, Encode, StringExt}, fp_utils, }; use error_stack::{report, ResultExt}; use fred::{ interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface}, prelude::{LuaInterface, RedisErrorKind}, types::{ Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings, MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse, }, }; use futures::StreamExt; use tracing::instrument; use crate::{ errors, types::{ DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply, SetnxReply, }, }; impl super::RedisConnectionPool { pub fn add_prefix(&self, key: &str) -> String { if self.key_prefix.is_empty() { key.to_string() } else { format!("{}:{}", self.key_prefix, key) } } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX(self.config.default_ttl.into())), None, false, ) .await .change_context(errors::RedisError::SetFailed) } pub async fn set_key_without_modifying_ttl<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::KEEPTTL), None, false, ) .await .change_context(errors::RedisError::SetFailed) } pub async fn set_multiple_keys_if_not_exist<V>( &self, value: V, ) -> CustomResult<MsetnxReply, errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .msetnx(value) .await .change_context(errors::RedisError::SetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_if_not_exist<V>( &self, key: &RedisKey, value: V, ttl: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key(key, serialized.as_slice()).await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_without_modifying_ttl<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_without_modifying_ttl(key, serialized.as_slice()) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.pool .set( key.tenant_aware_key(self), serialized.as_slice(), Some(Expiration::EX(seconds)), None, false, ) .await .change_context(errors::RedisError::SetExFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .get(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .get(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetFailed) } } } } #[instrument(level = "DEBUG", skip(self))] async fn get_multiple_keys_with_mget<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } let tenant_aware_keys: Vec<String> = keys.iter().map(|key| key.tenant_aware_key(self)).collect(); self.pool .mget(tenant_aware_keys) .await .change_context(errors::RedisError::GetFailed) } #[instrument(level = "DEBUG", skip(self))] async fn get_multiple_keys_with_parallel_get<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } let tenant_aware_keys: Vec<String> = keys.iter().map(|key| key.tenant_aware_key(self)).collect(); let futures = tenant_aware_keys .iter() .map(|redis_key| self.pool.get::<Option<V>, _>(redis_key)); let results = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::GetFailed) .attach_printable("Failed to get keys in cluster mode")?; Ok(results) } /// Helper method to encapsulate the logic for choosing between cluster and non-cluster modes #[instrument(level = "DEBUG", skip(self))] async fn get_keys_by_mode<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if self.config.cluster_enabled { // Use individual GET commands for cluster mode to avoid CROSSSLOT errors self.get_multiple_keys_with_parallel_get(keys).await } else { // Use MGET for non-cluster mode for better performance self.get_multiple_keys_with_mget(keys).await } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_multiple_keys<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } match self.get_keys_by_mode(keys).await { Ok(values) => Ok(values), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { let tenant_unaware_keys: Vec<RedisKey> = keys .iter() .map(|key| key.tenant_unaware_key(self).into()) .collect(); self.get_keys_by_mode(&tenant_unaware_keys).await } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError> where V: Into<MultipleKeys> + Unpin + Send + 'static, { match self .pool .exists(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .exists(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetFailed) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_key<T>( &self, key: &RedisKey, type_name: &'static str, ) -> CustomResult<T, errors::RedisError> where T: serde::de::DeserializeOwned, { let value_bytes = self.get_key::<Vec<u8>>(key).await?; fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?; value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_multiple_keys<T>( &self, keys: &[RedisKey], type_name: &'static str, ) -> CustomResult<Vec<Option<T>>, errors::RedisError> where T: serde::de::DeserializeOwned, { let value_bytes_vec = self.get_multiple_keys::<Vec<u8>>(keys).await?; let mut results = Vec::with_capacity(value_bytes_vec.len()); for value_bytes_opt in value_bytes_vec { match value_bytes_opt { Some(value_bytes) => { if value_bytes.is_empty() { results.push(None); } else { let parsed = value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed)?; results.push(Some(parsed)); } } None => results.push(None), } } Ok(results) } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> { match self .pool .del(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .del(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_multiple_keys( &self, keys: &[RedisKey], ) -> CustomResult<Vec<DelReply>, errors::RedisError> { let futures = keys.iter().map(|key| self.delete_key(key)); let del_result = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::DeleteFailed)?; Ok(del_result) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX(seconds)), None, false, ) .await .change_context(errors::RedisError::SetExFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_if_not_exists_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX( seconds.unwrap_or(self.config.default_ttl.into()), )), Some(SetOptions::NX), false, ) .await .change_context(errors::RedisError::SetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_expiry( &self, key: &RedisKey, seconds: i64, ) -> CustomResult<(), errors::RedisError> { self.pool .expire(key.tenant_aware_key(self), seconds) .await .change_context(errors::RedisError::SetExpiryFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_expire_at( &self, key: &RedisKey, timestamp: i64, ) -> CustomResult<(), errors::RedisError> { self.pool .expire_at(key.tenant_aware_key(self), timestamp) .await .change_context(errors::RedisError::SetExpiryFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> { self.pool .ttl(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_fields<V>( &self, key: &RedisKey, values: V, ttl: Option<i64>, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { let output: Result<(), _> = self .pool .hset(key.tenant_aware_key(self), values) .await .change_context(errors::RedisError::SetHashFailed); // setting expiry for the key output .async_and_then(|_| { self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into())) }) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_field_if_not_exist<V>( &self, key: &RedisKey, field: &str, value: V, ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { let output: Result<HsetnxReply, _> = self .pool .hsetnx(key.tenant_aware_key(self), field, value) .await .change_context(errors::RedisError::SetHashFieldFailed); output .async_and_then(|inner| async { self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into()) .await?; Ok(inner) }) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_hash_field_if_not_exist<V>( &self, key: &RedisKey, field: &str, value: V, ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>( &self, kv: &[(&RedisKey, V)], field: &str, ttl: Option<u32>, ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError> where V: serde::Serialize + Debug, { let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len()); for (key, val) in kv { hsetnx.push( self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl) .await?, ); } Ok(hsetnx) } #[instrument(level = "DEBUG", skip(self))] pub async fn increment_fields_in_hash<T>( &self, key: &RedisKey, fields_to_increment: &[(T, i64)], ) -> CustomResult<Vec<usize>, errors::RedisError> where T: Debug + ToString, { let mut values_after_increment = Vec::with_capacity(fields_to_increment.len()); for (field, increment) in fields_to_increment.iter() { values_after_increment.push( self.pool .hincrby(key.tenant_aware_key(self), field.to_string(), *increment) .await .change_context(errors::RedisError::IncrementHashFieldFailed)?, ) } Ok(values_after_increment) } #[instrument(level = "DEBUG", skip(self))] pub async fn hscan( &self, key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() .hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count) .filter_map(|value| async move { match value { Ok(mut v) => { let v = v.take_results()?; let v: Vec<String> = v.iter().filter_map(|(_, val)| val.as_string()).collect(); Some(futures::stream::iter(v)) } Err(err) => { tracing::error!(redis_err=?err, "Redis error while executing hscan command"); None } } }) .flatten() .collect::<Vec<_>>() .await) } #[instrument(level = "DEBUG", skip(self))] pub async fn scan( &self, pattern: &RedisKey, count: Option<u32>, scan_type: Option<ScanType>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() .scan(pattern.tenant_aware_key(self), count, scan_type) .filter_map(|value| async move { match value { Ok(mut v) => { let v = v.take_results()?; let v: Vec<String> = v.into_iter().filter_map(|val| val.into_string()).collect(); Some(futures::stream::iter(v)) } Err(err) => { tracing::error!(redis_err=?err, "Redis error while executing scan command"); None } } }) .flatten() .collect::<Vec<_>>() .await) } #[instrument(level = "DEBUG", skip(self))] pub async fn hscan_and_deserialize<T>( &self, key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<T>, errors::RedisError> where T: serde::de::DeserializeOwned, { let redis_results = self.hscan(key, pattern, count).await?; Ok(redis_results .iter() .filter_map(|v| { let r: T = v.parse_struct(std::any::type_name::<T>()).ok()?; Some(r) }) .collect()) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field<V>( &self, key: &RedisKey, field: &str, ) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .hget(key.tenant_aware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(feature = "multitenancy_fallback")] { self.pool .hget(key.tenant_unaware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) } #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .hgetall(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(feature = "multitenancy_fallback")] { self.pool .hgetall(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) } #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field_and_deserialize<V>( &self, key: &RedisKey, field: &str, type_name: &'static str, ) -> CustomResult<V, errors::RedisError> where V: serde::de::DeserializeOwned, { let value_bytes = self.get_hash_field::<Vec<u8>>(key, field).await?; if value_bytes.is_empty() { return Err(errors::RedisError::NotFound.into()); } value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn sadd<V>( &self, key: &RedisKey, members: V, ) -> CustomResult<SaddReply, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send, V::Error: Into<fred::error::RedisError> + Send, { self.pool .sadd(key.tenant_aware_key(self), members) .await .change_context(errors::RedisError::SetAddMembersFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_append_entry<F>( &self, stream: &RedisKey, entry_id: &RedisEntryId, fields: F, ) -> CustomResult<(), errors::RedisError> where F: TryInto<MultipleOrderedPairs> + Debug + Send + Sync, F::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .xadd(stream.tenant_aware_key(self), false, None, entry_id, fields) .await .change_context(errors::RedisError::StreamAppendFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_delete_entries<Ids>( &self, stream: &RedisKey, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleStrings> + Debug + Send + Sync, { self.pool .xdel(stream.tenant_aware_key(self), ids) .await .change_context(errors::RedisError::StreamDeleteFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_trim_entries<C>( &self, stream: &RedisKey, xcap: C, ) -> CustomResult<usize, errors::RedisError> where C: TryInto<XCap> + Debug + Send + Sync, C::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .xtrim(stream.tenant_aware_key(self), xcap) .await .change_context(errors::RedisError::StreamTrimFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_acknowledge_entries<Ids>( &self, stream: &RedisKey, group: &str, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleIDs> + Debug + Send + Sync, { self.pool .xack(stream.tenant_aware_key(self), group, ids) .await .change_context(errors::RedisError::StreamAcknowledgeFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_get_length( &self, stream: &RedisKey, ) -> CustomResult<usize, errors::RedisError> { self.pool .xlen(stream.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetLengthFailed) } pub fn get_keys_with_prefix<K>(&self, keys: K) -> MultipleKeys where K: Into<MultipleKeys> + Debug + Send + Sync, { let multiple_keys: MultipleKeys = keys.into(); let res = multiple_keys .inner() .iter() .filter_map(|key| key.as_str().map(RedisKey::from)) .map(|k: RedisKey| k.tenant_aware_key(self)) .collect::<Vec<_>>(); MultipleKeys::from(res) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_read_entries<K, Ids>( &self, streams: K, ids: Ids, read_count: Option<u64>, ) -> CustomResult<XReadResponse<String, String, String, String>, errors::RedisError> where K: Into<MultipleKeys> + Debug + Send + Sync, Ids: Into<MultipleIDs> + Debug + Send + Sync, { let strms = self.get_keys_with_prefix(streams); self.pool .xread_map( Some(read_count.unwrap_or(self.config.default_stream_read_count)), None, strms, ids, ) .await .map_err(|err| match err.kind() { RedisErrorKind::NotFound | RedisErrorKind::Parse => { report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable) } _ => report!(err).change_context(errors::RedisError::StreamReadFailed), }) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_read_with_options<K, Ids>( &self, streams: K, ids: Ids, count: Option<u64>, block: Option<u64>, // timeout in milliseconds group: Option<(&str, &str)>, // (group_name, consumer_name) ) -> CustomResult<XReadResponse<String, String, String, Option<String>>, errors::RedisError> where K: Into<MultipleKeys> + Debug + Send + Sync, Ids: Into<MultipleIDs> + Debug + Send + Sync, { match group { Some((group_name, consumer_name)) => { self.pool .xreadgroup_map( group_name, consumer_name, count, block, false, self.get_keys_with_prefix(streams), ids, ) .await } None => { self.pool .xread_map(count, block, self.get_keys_with_prefix(streams), ids) .await } } .map_err(|err| match err.kind() { RedisErrorKind::NotFound | RedisErrorKind::Parse => { report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable) } _ => report!(err).change_context(errors::RedisError::StreamReadFailed), }) } #[instrument(level = "DEBUG", skip(self))] pub async fn append_elements_to_list<V>( &self, key: &RedisKey, elements: V, ) -> CustomResult<(), errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send, V::Error: Into<fred::error::RedisError> + Send, { self.pool .rpush(key.tenant_aware_key(self), elements) .await .change_context(errors::RedisError::AppendElementsToListFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_elements( &self, key: &RedisKey, start: i64, stop: i64, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool .lrange(key.tenant_aware_key(self), start, stop) .await .change_context(errors::RedisError::GetListElementsFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> { self.pool .llen(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetListLengthFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn lpop_list_elements( &self, key: &RedisKey, count: Option<usize>, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool .lpop(key.tenant_aware_key(self), count) .await .change_context(errors::RedisError::PopListElementsFailed) } // Consumer Group API #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_create( &self, stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<(), errors::RedisError> { if matches!( id, RedisEntryId::AutoGeneratedID | RedisEntryId::UndeliveredEntryID ) { // FIXME: Replace with utils::when Err(errors::RedisError::InvalidRedisEntryId)?; } self.pool .xgroup_create(stream.tenant_aware_key(self), group, id, true) .await .change_context(errors::RedisError::ConsumerGroupCreateFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_destroy( &self, stream: &RedisKey, group: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool .xgroup_destroy(stream.tenant_aware_key(self), group) .await .change_context(errors::RedisError::ConsumerGroupDestroyFailed) } // the number of pending messages that the consumer had before it was deleted #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_delete_consumer( &self, stream: &RedisKey, group: &str, consumer: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool .xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer) .await .change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/build.rs
crates/router/build.rs
fn main() { // Set thread stack size to 11 MiB for debug builds // Reference: https://doc.rust-lang.org/std/thread/#stack-size #[cfg(debug_assertions)] println!("cargo:rustc-env=RUST_MIN_STACK=11534336"); // 11 * 1024 * 1024 = 11 MiB #[cfg(feature = "vergen")] router_env::vergen::generate_cargo_instructions(); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db.rs
crates/router/src/db.rs
pub mod address; pub mod api_keys; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod blocklist_lookup; pub mod business_profile; pub mod callback_mapper; pub mod capture; pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; pub mod dynamic_routing_stats; pub mod ephemeral_key; pub mod events; pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod health_check; pub mod hyperswitch_ai_interaction; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod organization; pub mod payment_link; pub mod payment_method_session; pub mod refund; pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod unified_translations; pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; use ::payment_methods::state::PaymentMethodsStorageInterface; use common_utils::{id_type, types::keymanager::KeyManagerState}; use diesel_models::{ fraud_check::{FraudCheck, FraudCheckUpdate}, organization::{Organization, OrganizationNew, OrganizationUpdate}, }; use error_stack::ResultExt; #[cfg(feature = "payouts")] use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface, }; use hyperswitch_domain_models::{ cards_info::CardsInfoInterface, master_key::MasterKeyInterface, payment_methods::PaymentMethodInterface, payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface}, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use redis_interface::errors::RedisError; use router_env::logger; use storage_impl::{ errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb, }; pub use self::kafka_store::KafkaStore; use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; pub use crate::{ core::errors::{self, ProcessTrackerError}, errors::CustomResult, services::{ kafka::{KafkaError, KafkaProducer, MQResult}, Store, }, types::{ domain, storage::{self}, AccessToken, }, }; #[derive(PartialEq, Eq)] pub enum StorageImpl { Postgresql, PostgresqlTest, Mock, } #[async_trait::async_trait] pub trait StorageInterface: Send + Sync + dyn_clone::DynClone + address::AddressInterface + api_keys::ApiKeyInterface + blocklist_lookup::BlocklistLookupInterface + configs::ConfigInterface<Error = StorageError> + capture::CaptureInterface + customers::CustomerInterface<Error = StorageError> + dashboard_metadata::DashboardMetadataInterface + dispute::DisputeInterface + ephemeral_key::EphemeralKeyInterface + ephemeral_key::ClientSecretInterface + events::EventInterface + file::FileMetadataInterface + FraudCheckInterface + locker_mock_up::LockerMockUpInterface + mandate::MandateInterface + merchant_account::MerchantAccountInterface<Error = StorageError> + merchant_connector_account::ConnectorAccessToken + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError> + PaymentAttemptInterface<Error = StorageError> + PaymentIntentInterface<Error = StorageError> + PaymentMethodInterface<Error = StorageError> + blocklist::BlocklistInterface + blocklist_fingerprint::BlocklistFingerprintInterface + dynamic_routing_stats::DynamicRoutingStatsInterface + scheduler::SchedulerInterface + PayoutAttemptInterface<Error = StorageError> + PayoutsInterface<Error = StorageError> + refund::RefundInterface + reverse_lookup::ReverseLookupInterface + CardsInfoInterface<Error = StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError> + MasterKeyInterface + payment_link::PaymentLinkInterface + RedisConnInterface + RequestIdStore + business_profile::ProfileInterface<Error = StorageError> + routing_algorithm::RoutingAlgorithmInterface + gsm::GsmInterface + unified_translations::UnifiedTranslationsInterface + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + user_authentication_method::UserAuthenticationMethodInterface + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface + authentication::AuthenticationInterface + generic_link::GenericLinkInterface + relay::RelayInterface + user::theme::ThemeInterface + payment_method_session::PaymentMethodsSessionInterface + tokenization::TokenizationInterface + callback_mapper::CallbackMapperInterface + storage_impl::subscription::SubscriptionInterface<Error = StorageError> + storage_impl::invoice::InvoiceInterface<Error = StorageError> + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>; fn get_subscription_store(&self) -> Box<dyn subscriptions::state::SubscriptionStorageInterface>; fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState); } #[async_trait::async_trait] pub trait GlobalStorageInterface: Send + Sync + dyn_clone::DynClone + user::UserInterface + user_role::UserRoleInterface + user_key_store::UserKeyStoreInterface + role::RoleInterface + RedisConnInterface + 'static { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] pub trait AccountsStorageInterface: Send + Sync + dyn_clone::DynClone + OrganizationInterface + merchant_account::MerchantAccountInterface<Error = StorageError> + business_profile::ProfileInterface<Error = StorageError> + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError> + dashboard_metadata::DashboardMetadataInterface + 'static { } pub trait CommonStorageInterface: StorageInterface + GlobalStorageInterface + AccountsStorageInterface + PaymentMethodsStorageInterface { fn get_storage_interface(&self) -> Box<dyn StorageInterface>; fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface>; fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface>; } #[async_trait::async_trait] impl StorageInterface for Store { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) { self.key_manager_state = Some(key_manager_state.clone()); #[cfg(feature = "kv_store")] self.router_store.set_key_manager_state(key_manager_state); } } #[async_trait::async_trait] impl GlobalStorageInterface for Store { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for Store {} #[async_trait::async_trait] impl StorageInterface for MockDb { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) { self.key_manager_state = Some(key_manager_state); } } #[async_trait::async_trait] impl GlobalStorageInterface for MockDb { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for MockDb {} impl CommonStorageInterface for MockDb { fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } impl CommonStorageInterface for Store { fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } pub trait RequestIdStore { fn add_request_id(&mut self, _request_id: String) {} fn get_request_id(&self) -> Option<String> { None } } impl RequestIdStore for MockDb {} impl RequestIdStore for Store { fn add_request_id(&mut self, request_id: String) { self.request_id = Some(request_id) } fn get_request_id(&self) -> Option<String> { self.request_id.clone() } } pub async fn get_and_deserialize_key<T>( db: &dyn StorageInterface, key: &str, type_name: &'static str, ) -> CustomResult<T, RedisError> where T: serde::de::DeserializeOwned, { use common_utils::ext_traits::ByteSliceExt; let bytes = db.get_key(key).await?; bytes .parse_struct(type_name) .change_context(RedisError::JsonDeserializationFailed) } dyn_clone::clone_trait_object!(StorageInterface); dyn_clone::clone_trait_object!(GlobalStorageInterface); dyn_clone::clone_trait_object!(AccountsStorageInterface); impl RequestIdStore for KafkaStore { fn add_request_id(&mut self, request_id: String) { self.diesel_store.add_request_id(request_id) } } #[async_trait::async_trait] impl FraudCheckInterface for KafkaStore { async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, StorageError> { let frm = self.diesel_store.insert_fraud_check_response(new).await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message = "Failed to log analytics event for fraud check", error_message = ?er); } Ok(frm) } async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, StorageError> { let frm = self .diesel_store .update_fraud_check_response_with_attempt_id(this, fraud_check) .await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) } Ok(frm) } async fn find_fraud_check_by_payment_id( &self, payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult<FraudCheck, StorageError> { let frm = self .diesel_store .find_fraud_check_by_payment_id(payment_id, merchant_id) .await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) } Ok(frm) } async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, StorageError> { let frm = self .diesel_store .find_fraud_check_by_payment_id_if_present(payment_id, merchant_id) .await?; if let Some(fraud_check) = frm.clone() { if let Err(er) = self .kafka_producer .log_fraud_check(&fraud_check, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er); } } Ok(frm) } } #[async_trait::async_trait] impl OrganizationInterface for KafkaStore { async fn insert_organization( &self, organization: OrganizationNew, ) -> CustomResult<Organization, StorageError> { self.diesel_store.insert_organization(organization).await } async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<Organization, StorageError> { self.diesel_store.find_organization_by_org_id(org_id).await } async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: OrganizationUpdate, ) -> CustomResult<Organization, StorageError> { self.diesel_store .update_organization_by_org_id(org_id, update) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/consts.rs
crates/router/src/consts.rs
pub mod oidc; pub mod opensearch; #[cfg(feature = "olap")] pub mod user; pub mod user_role; use std::{collections::HashSet, str::FromStr, sync}; use api_models::enums::Country; use common_utils::{consts, id_type}; pub use hyperswitch_domain_models::consts::{ CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, ROUTING_ENABLED_PAYMENT_METHODS, ROUTING_ENABLED_PAYMENT_METHOD_TYPES, }; pub use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; // ID generation pub(crate) const ID_LENGTH: usize = 20; pub(crate) const MAX_ID_LENGTH: usize = 64; #[rustfmt::skip] pub(crate) const ALPHABETS: [char; 62] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ]; /// API client request timeout (in seconds) pub const REQUEST_TIME_OUT: u64 = 30; pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; pub const REQUEST_TIMEOUT_PAYMENT_NOT_FOUND: &str = "Timed out ,payment not found"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str = "This Payment has been moved to failed as there is no response from the connector"; ///Payment intent fulfillment default timeout (in seconds) pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; /// The length of a merchant fingerprint secret pub const FINGERPRINT_SECRET_LENGTH: usize = 64; pub const DEFAULT_LIST_API_LIMIT: u16 = 10; // String literals pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type"; // General purpose base64 engines pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = consts::BASE64_ENGINE; pub(crate) const API_KEY_LENGTH: usize = 64; // OID (Object Identifier) for the merchant ID field extension. pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32"; pub const MAX_ROUTING_CONFIGS_PER_MERCHANT: usize = 100; pub const ROUTING_CONFIG_ID_LENGTH: usize = 10; pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN"; pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days // This should be one day, but it is causing issue while checking token in blacklist. // TODO: This should be fixed in future. pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token"; pub const USER_BLACKLIST_PREFIX: &str = "BU_"; pub const ROLE_BLACKLIST_PREFIX: &str = "BR_"; #[cfg(feature = "email")] pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day #[cfg(feature = "email")] pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; pub const EMAIL_SUBJECT_API_KEY_EXPIRY: &str = "API Key Expiry Notice"; pub const EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST: &str = "Dashboard Pro Feature Request by"; pub const EMAIL_SUBJECT_APPROVAL_RECON_REQUEST: &str = "Approval of Recon Request - Access Granted to Recon Dashboard"; pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_"; pub const CARD_IP_BLOCKING_CACHE_KEY_PREFIX: &str = "CARD_IP_BLOCKING"; pub const GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX: &str = "GUEST_USER_CARD_BLOCKING"; pub const CUSTOMER_ID_BLOCKING_PREFIX: &str = "CUSTOMER_ID_BLOCKING"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; #[cfg(feature = "olap")] pub const CONNECTOR_ONBOARDING_CONFIG_PREFIX: &str = "onboarding"; /// Max payment session expiry pub const MAX_SESSION_EXPIRY: u32 = 7890000; /// Min payment session expiry pub const MIN_SESSION_EXPIRY: u32 = 60; /// Max payment intent fulfillment expiry pub const MAX_INTENT_FULFILLMENT_EXPIRY: u32 = 1800; /// Min payment intent fulfillment expiry pub const MIN_INTENT_FULFILLMENT_EXPIRY: u32 = 60; pub const LOCKER_HEALTH_CALL_PATH: &str = "/health"; pub const LOCKER_ADD_CARD_PATH: &str = "/cards/add"; pub const LOCKER_RETRIEVE_CARD_PATH: &str = "/cards/retrieve"; pub const LOCKER_DELETE_CARD_PATH: &str = "/cards/delete"; pub const AUTHENTICATION_ID_PREFIX: &str = "authn"; // URL for checking the outgoing call pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck"; // 15 minutes = 900 seconds pub const POLL_ID_TTL: i64 = 900; // 15 minutes = 900 seconds pub const AUTHENTICATION_ELIGIBILITY_CHECK_DATA_TTL: i64 = 900; // Prefix key for storing authentication eligibility check data in redis pub const AUTHENTICATION_ELIGIBILITY_CHECK_DATA_KEY: &str = "AUTH_ELIGIBILITY_CHECK_DATA_"; // Default Poll Config pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2; pub const DEFAULT_POLL_FREQUENCY: i8 = 5; // Number of seconds to subtract from access token expiry pub(crate) const REDUCE_ACCESS_TOKEN_EXPIRY_TIME: u8 = 15; pub const CONNECTOR_CREDS_TOKEN_TTL: i64 = 900; //max_amount allowed is 999999999 in minor units pub const MAX_ALLOWED_AMOUNT: i64 = 999999999; //payment attempt default unified error code and unified error message pub const DEFAULT_UNIFIED_ERROR_CODE: &str = "UE_9000"; pub const DEFAULT_UNIFIED_ERROR_MESSAGE: &str = "Something went wrong"; // Recon's feature tag pub const RECON_FEATURE_TAG: &str = "RECONCILIATION AND SETTLEMENT"; /// Default allowed domains for payment links pub const DEFAULT_ALLOWED_DOMAINS: Option<HashSet<String>> = None; /// Default hide card nickname field pub const DEFAULT_HIDE_CARD_NICKNAME_FIELD: bool = false; /// Show card form by default for payment links pub const DEFAULT_SHOW_CARD_FORM: bool = true; /// Default bool for Display sdk only pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; /// Default bool to enable saved payment method pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; /// [PaymentLink] Default bool for enabling button only when form is ready pub const DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY: bool = false; /// Default Merchant Logo Link pub const DEFAULT_MERCHANT_LOGO: &str = "https://live.hyperswitch.io/payment-link-assets/Merchant_placeholder.png"; /// Default Payment Link Background color pub const DEFAULT_BACKGROUND_COLOR: &str = "#212E46"; /// Default product Img Link pub const DEFAULT_PRODUCT_IMG: &str = "https://live.hyperswitch.io/payment-link-assets/cart_placeholder.png"; /// Default SDK Layout pub const DEFAULT_SDK_LAYOUT: &str = "tabs"; /// Vault Add request url #[cfg(feature = "v2")] pub const ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add"; /// Vault Get Fingerprint request url #[cfg(feature = "v2")] pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint"; /// Vault Retrieve request url #[cfg(feature = "v2")] pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve"; /// Vault Delete request url #[cfg(feature = "v2")] pub const VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete"; /// Vault Header content type #[cfg(feature = "v2")] pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json"; /// Vault Add flow type #[cfg(feature = "v2")] pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault"; /// Vault Retrieve flow type #[cfg(feature = "v2")] pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault"; /// Vault Delete flow type #[cfg(feature = "v2")] pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault"; /// Vault Fingerprint fetch flow type #[cfg(feature = "v2")] pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault"; /// Max volume split for Dynamic routing pub const DYNAMIC_ROUTING_MAX_VOLUME: u8 = 100; /// Click To Pay pub const CLICK_TO_PAY: &str = "click_to_pay"; /// Merchant eligible for authentication service config pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str = "merchants_eligible_for_authentication_service"; /// Payment flow identifier used for performing GSM operations pub const PAYMENT_FLOW_STR: &str = "Payment"; /// Default subflow identifier used for performing GSM operations pub const DEFAULT_SUBFLOW_STR: &str = "sub_flow"; /// Refund flow identifier used for performing GSM operations pub const REFUND_FLOW_STR: &str = "refund_flow"; /// Minimum IBAN length (country-dependent), as per ISO 13616 standard pub const IBAN_MIN_LENGTH: usize = 15; /// Maximum IBAN length defined by the ISO 13616 standard (standard max) pub const IBAN_MAX_LENGTH: usize = 34; /// Minimum UK BACS account number length in digits pub const BACS_MIN_ACCOUNT_NUMBER_LENGTH: usize = 6; /// Maximum UK BACS account number length in digits pub const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8; /// Fixed length of UK BACS sort code in digits (always 6) pub const BACS_SORT_CODE_LENGTH: usize = 6; /// Exact length of Polish Elixir system domestic account number (NRB) in digits pub const ELIXIR_ACCOUNT_NUMBER_LENGTH: usize = 26; /// Total length of Polish IBAN including country code and checksum (28 characters) pub const ELIXIR_IBAN_LENGTH: usize = 28; /// Minimum length of Swedish Bankgiro number in digits pub const BANKGIRO_MIN_LENGTH: usize = 7; /// Maximum length of Swedish Bankgiro number in digits pub const BANKGIRO_MAX_LENGTH: usize = 8; /// Minimum length of Swedish Plusgiro number in digits pub const PLUSGIRO_MIN_LENGTH: usize = 2; /// Maximum length of Swedish Plusgiro number in digits pub const PLUSGIRO_MAX_LENGTH: usize = 8; /// Default payment method session expiry pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes /// Authorize flow identifier used for performing GSM operations pub const AUTHORIZE_FLOW_STR: &str = "Authorize"; /// Protocol Version for encrypted Google Pay Token pub(crate) const PROTOCOL: &str = "ECv2"; /// Sender ID for Google Pay Decryption pub(crate) const SENDER_ID: &[u8] = b"Google"; /// Default value for the number of attempts to retry fetching forex rates pub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3; /// Default payment intent id pub const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id"; /// Default payment attempt id pub const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id"; pub static PROFILE_ID_UNAVAILABLE: sync::LazyLock<id_type::ProfileId> = sync::LazyLock::new(|| { #[allow(clippy::expect_used)] id_type::ProfileId::from_str("PROFILE_ID_UNAVAIABLE") .expect("Failed to parse PROFILE_ID_UNAVAIABLE") }); /// Default payment attempt id pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID: &str = "irrelevant_connector_request_reference_id"; // Default payment method storing TTL in redis in seconds pub const DEFAULT_PAYMENT_METHOD_STORE_TTL: i64 = 86400; // 1 day // List of countries that are part of the PSD2 region pub const PSD2_COUNTRIES: [Country; 27] = [ Country::Austria, Country::Belgium, Country::Bulgaria, Country::Croatia, Country::Cyprus, Country::Czechia, Country::Denmark, Country::Estonia, Country::Finland, Country::France, Country::Germany, Country::Greece, Country::Hungary, Country::Ireland, Country::Italy, Country::Latvia, Country::Lithuania, Country::Luxembourg, Country::Malta, Country::Netherlands, Country::Poland, Country::Portugal, Country::Romania, Country::Slovakia, Country::Slovenia, Country::Spain, Country::Sweden, ]; // Rollout percentage config prefix pub const UCS_ROLLOUT_PERCENT_CONFIG_PREFIX: &str = "ucs_rollout_config"; // UCS feature enabled config pub const UCS_ENABLED: &str = "ucs_enabled"; /// Header value indicating that signature-key-based authentication is used. pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key"; /// Header value indicating that body-key-based authentication is used. pub const UCS_AUTH_BODY_KEY: &str = "body-key"; /// Header value indicating that header-key-based authentication is used. pub const UCS_AUTH_HEADER_KEY: &str = "header-key"; /// Header value indicating that multi-key-based authentication is used. pub const UCS_AUTH_MULTI_KEY: &str = "multi-auth-key"; /// Header value indicating that currency-auth-key-based authentication is used. pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key"; /// Form field name for challenge request during creq submission pub const CREQ_CHALLENGE_REQUEST_KEY: &str = "creq"; /// Superposition configuration keys pub mod superposition { /// CVV requirement configuration key pub const REQUIRES_CVV: &str = "requires_cvv"; } #[cfg(test)] mod tests { #[test] fn test_profile_id_unavailable_initialization() { // Just access the lazy static to ensure it doesn't panic during initialization let _profile_id = super::PROFILE_ID_UNAVAILABLE.clone(); // If we get here without panicking, the test passes } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility.rs
crates/router/src/compatibility.rs
pub mod stripe; pub mod wrap;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services.rs
crates/router/src/services.rs
pub mod api; pub mod authentication; pub mod authorization; pub mod connector_integration_interface; #[cfg(feature = "email")] pub mod email; pub mod encryption; #[cfg(feature = "olap")] pub mod jwt; pub mod kafka; pub mod logger; pub mod pm_auth; pub mod card_testing_guard; #[cfg(feature = "olap")] pub mod oidc_provider; #[cfg(feature = "olap")] pub mod openidconnect; use std::sync::Arc; use common_utils::types::{keymanager, TenantConfig}; use error_stack::ResultExt; pub use hyperswitch_interfaces::connector_integration_v2::{ BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2, }; use masking::{ExposeInterface, StrongSecret}; #[cfg(feature = "kv_store")] use storage_impl::kv_router_store::KVRouterStore; use storage_impl::{errors::StorageResult, redis::RedisStore, RouterStore}; use tokio::sync::oneshot; pub use self::{api::*, encryption::*}; use crate::{configs::Settings, core::errors}; #[cfg(not(feature = "olap"))] pub type StoreType = storage_impl::database::store::Store; #[cfg(feature = "olap")] pub type StoreType = storage_impl::database::store::ReplicaStore; #[cfg(not(feature = "kv_store"))] pub type Store = RouterStore<StoreType>; #[cfg(feature = "kv_store")] pub type Store = KVRouterStore<StoreType>; /// # Panics /// /// Will panic if hex decode of master key fails #[allow(clippy::expect_used)] pub async fn get_store( config: &Settings, tenant: &dyn TenantConfig, cache_store: Arc<RedisStore>, test_transaction: bool, key_manager_state: keymanager::KeyManagerState, ) -> StorageResult<Store> { let master_config = config.master_database.clone().into_inner(); #[cfg(feature = "olap")] let replica_config = config.replica_database.clone().into_inner(); #[allow(clippy::expect_used)] let master_enc_key = hex::decode(config.secrets.get_inner().master_enc_key.clone().expose()) .map(StrongSecret::new) .expect("Failed to decode master key from hex"); #[cfg(not(feature = "olap"))] let conf = master_config.into(); #[cfg(feature = "olap")] // this would get abstracted, for all cases #[allow(clippy::useless_conversion)] let conf = (master_config.into(), replica_config.into()); let store: RouterStore<StoreType> = if test_transaction { RouterStore::test_store( conf, tenant, &config.redis, master_enc_key, Some(key_manager_state.clone()), ) .await? } else { RouterStore::from_config( conf, tenant, master_enc_key, cache_store, storage_impl::redis::cache::IMC_INVALIDATION_CHANNEL, Some(key_manager_state.clone()), ) .await? }; #[cfg(feature = "kv_store")] let store = KVRouterStore::from_store( store, config.drainer.stream_name.clone(), config.drainer.num_partitions, config.kv_config.ttl, config.kv_config.soft_kill, Some(key_manager_state), ); Ok(store) } #[allow(clippy::expect_used)] pub async fn get_cache_store( config: &Settings, shut_down_signal: oneshot::Sender<()>, _test_transaction: bool, ) -> StorageResult<Arc<RedisStore>> { RouterStore::<StoreType>::cache_store(&config.redis, shut_down_signal).await } #[inline] pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> { use ring::rand::SecureRandom; let rng = ring::rand::SystemRandom::new(); let mut key: [u8; 256 / 8] = [0_u8; 256 / 8]; rng.fill(&mut key) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(key) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/lib.rs
crates/router/src/lib.rs
#[cfg(all(feature = "stripe", feature = "v1"))] pub mod compatibility; pub mod configs; pub mod connection; pub mod connector; pub mod consts; pub mod core; pub mod cors; pub mod db; pub mod env; pub mod locale; pub(crate) mod macros; pub mod routes; pub mod workflows; #[cfg(feature = "olap")] pub mod analytics; pub mod analytics_validator; pub mod events; pub mod middleware; pub mod services; pub mod types; pub mod utils; use actix_web::{ body::MessageBody, dev::{Server, ServerHandle, ServiceFactory, ServiceRequest}, middleware::ErrorHandlers, }; use http::StatusCode; use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret; use router_env::tracing::Instrument; use routes::{AppState, SessionState}; use storage_impl::errors::ApplicationResult; use tokio::sync::{mpsc, oneshot}; pub use self::env::logger; pub(crate) use self::macros::*; use crate::{configs::settings, core::errors}; #[cfg(feature = "mimalloc")] #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; // Import translate fn in root use crate::locale::{_rust_i18n_t, _rust_i18n_try_translate}; /// Header Constants pub mod headers { pub const ACCEPT: &str = "Accept"; pub const ACCEPT_LANGUAGE: &str = "Accept-Language"; pub const KEY: &str = "key"; pub const API_KEY: &str = "API-KEY"; pub const APIKEY: &str = "apikey"; pub const X_CC_API_KEY: &str = "X-CC-Api-Key"; pub const API_TOKEN: &str = "Api-Token"; pub const AUTHORIZATION: &str = "Authorization"; pub const CONTENT_TYPE: &str = "Content-Type"; pub const DATE: &str = "Date"; pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; pub const NONCE: &str = "nonce"; pub const TIMESTAMP: &str = "Timestamp"; pub const TOKEN: &str = "token"; pub const USER_AGENT: &str = "User-Agent"; pub const X_API_KEY: &str = "X-API-KEY"; pub const X_API_VERSION: &str = "X-ApiVersion"; pub const X_FORWARDED_FOR: &str = "X-Forwarded-For"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key"; pub const X_ORGANIZATION_ID: &str = "X-Organization-Id"; pub const X_LOGIN: &str = "X-Login"; pub const X_TRANS_KEY: &str = "X-Trans-Key"; pub const X_VERSION: &str = "X-Version"; pub const X_CC_VERSION: &str = "X-CC-Version"; pub const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub const X_DATE: &str = "X-Date"; pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512"; pub const X_REQUEST_ID: &str = "X-Request-Id"; pub const X_PROFILE_ID: &str = "X-Profile-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub const X_CLIENT_VERSION: &str = "X-Client-Version"; pub const X_CLIENT_SOURCE: &str = "X-Client-Source"; pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source"; pub const CONTENT_LENGTH: &str = "Content-Length"; pub const BROWSER_NAME: &str = "x-browser-name"; pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain"; pub const X_APP_ID: &str = "x-app-id"; pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; pub const X_CUSTOMER_ID: &str = "X-Customer-Id"; pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id"; // Header value for X_CONNECTOR_HTTP_STATUS_CODE differs by version. // Constant name is kept the same for consistency across versions. #[cfg(feature = "v1")] pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "connector_http_status_code"; #[cfg(feature = "v2")] pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "x-connector-http-status-code"; pub const X_REFERENCE_ID: &str = "X-Reference-Id"; } pub mod pii { //! Personal Identifiable Information protection. pub(crate) use common_utils::pii::Email; #[doc(inline)] pub use masking::*; } pub fn mk_app( state: AppState, request_body_limit: usize, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, Config = (), Response = actix_web::dev::ServiceResponse<impl MessageBody>, Error = actix_web::Error, InitError = (), >, > { let mut server_app = get_application_builder( request_body_limit, state.conf.cors.clone(), state.conf.trace_header.clone(), ); #[cfg(feature = "dummy_connector")] { use routes::DummyConnector; server_app = server_app.service(DummyConnector::server(state.clone())); } #[cfg(any(feature = "olap", feature = "oltp"))] { #[cfg(feature = "olap")] { // This is a more specific route as compared to `MerchantConnectorAccount` // so it is registered before `MerchantConnectorAccount`. #[cfg(feature = "v1")] { server_app = server_app .service(routes::ProfileNew::server(state.clone())) .service(routes::Forex::server(state.clone())) .service(routes::ProfileAcquirer::server(state.clone())); } server_app = server_app.service(routes::Profile::server(state.clone())); } server_app = server_app .service(routes::Payments::server(state.clone())) .service(routes::Customers::server(state.clone())) .service(routes::Configs::server(state.clone())) .service(routes::MerchantConnectorAccount::server(state.clone())) .service(routes::RelayWebhooks::server(state.clone())) .service(routes::Webhooks::server(state.clone())) .service(routes::Hypersense::server(state.clone())) .service(routes::Relay::server(state.clone())) .service(routes::ThreeDsDecisionRule::server(state.clone())); #[cfg(feature = "oltp")] { server_app = server_app.service(routes::PaymentMethods::server(state.clone())); } #[cfg(all(feature = "v2", feature = "oltp"))] { server_app = server_app .service(routes::PaymentMethodSession::server(state.clone())) .service(routes::Refunds::server(state.clone())); } #[cfg(all(feature = "v2", feature = "oltp", feature = "tokenization_v2"))] { server_app = server_app.service(routes::Tokenization::server(state.clone())); } #[cfg(feature = "v1")] { server_app = server_app .service(routes::Refunds::server(state.clone())) .service(routes::Mandates::server(state.clone())) .service(routes::Authentication::server(state.clone())); } } #[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))] { server_app = server_app.service(routes::EphemeralKey::server(state.clone())) } #[cfg(all(feature = "oltp", feature = "v1"))] { server_app = server_app.service(routes::Poll::server(state.clone())) } #[cfg(feature = "olap")] { server_app = server_app .service(routes::Organization::server(state.clone())) .service(routes::MerchantAccount::server(state.clone())) .service(routes::User::server(state.clone())) .service(routes::ApiKeys::server(state.clone())) .service(routes::Routing::server(state.clone())) .service(routes::Chat::server(state.clone())); #[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))] { server_app = server_app.service(routes::Verify::server(state.clone())); } #[cfg(feature = "v1")] { server_app = server_app .service(routes::Files::server(state.clone())) .service(routes::Disputes::server(state.clone())) .service(routes::Blocklist::server(state.clone())) .service(routes::Subscription::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) .service(routes::ConnectorOnboarding::server(state.clone())) .service(routes::Analytics::server(state.clone())) .service(routes::WebhookEvents::server(state.clone())) .service(routes::FeatureMatrix::server(state.clone())); } #[cfg(feature = "v2")] { server_app = server_app .service(routes::UserDeprecated::server(state.clone())) .service(routes::ProcessTrackerDeprecated::server(state.clone())) .service(routes::ProcessTracker::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::RecoveryDataBackfill::server(state.clone())); } } #[cfg(all(feature = "payouts", feature = "v1"))] { server_app = server_app .service(routes::Payouts::server(state.clone())) .service(routes::PayoutLink::server(state.clone())); } #[cfg(all(feature = "stripe", feature = "v1"))] { server_app = server_app .service(routes::StripeApis::server(state.clone())) .service(routes::Cards::server(state.clone())); } #[cfg(all(feature = "oltp", feature = "v2"))] { server_app = server_app.service(routes::Proxy::server(state.clone())); } #[cfg(all(feature = "recon", feature = "v1"))] { server_app = server_app.service(routes::Recon::server(state.clone())); } server_app = server_app.service(routes::Cache::server(state.clone())); server_app = server_app.service(routes::Health::server(state.clone())); // Registered at the end because this entry has an empty scope #[cfg(feature = "olap")] { server_app = server_app.service(routes::Oidc::server(state.clone())); } server_app } /// Starts the server /// /// # Panics /// /// Unwrap used because without the value we can't start the server #[allow(clippy::expect_used, clippy::unwrap_used)] pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> { logger::debug!(startup_config=?conf); let server = conf.server.clone(); let (tx, rx) = oneshot::channel(); let api_client = Box::new(services::ProxyClient::new(&conf.proxy).map_err(|error| { errors::ApplicationError::ApiClientError(error.current_context().clone()) })?); let state = Box::pin(AppState::new(conf, tx, api_client)).await; let request_body_limit = server.request_body_limit; let server_builder = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) .bind((server.host.as_str(), server.port))? .workers(server.workers) .shutdown_timeout(server.shutdown_timeout); #[cfg(feature = "tls")] let server = match server.tls { None => server_builder.run(), Some(tls_conf) => { let cert_file = &mut std::io::BufReader::new(std::fs::File::open(tls_conf.certificate).map_err( |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), )?); let key_file = &mut std::io::BufReader::new(std::fs::File::open(tls_conf.private_key).map_err( |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), )?); let cert_chain = rustls_pemfile::certs(cert_file) .collect::<Result<Vec<_>, _>>() .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; let mut keys = rustls_pemfile::pkcs8_private_keys(key_file) .map(|key| key.map(rustls::pki_types::PrivateKeyDer::Pkcs8)) .collect::<Result<Vec<_>, _>>() .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; // exit if no keys could be parsed if keys.is_empty() { return Err(errors::ApplicationError::InvalidConfigurationValueError( "Could not locate PKCS8 private keys.".into(), )); } let config_builder = rustls::ServerConfig::builder().with_no_client_auth(); let config = config_builder .with_single_cert(cert_chain, keys.remove(0)) .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; server_builder .bind_rustls_0_22( (tls_conf.host.unwrap_or(server.host).as_str(), tls_conf.port), config, )? .run() } }; #[cfg(not(feature = "tls"))] let server = server_builder.run(); let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span()); Ok(server) } pub async fn receiver_for_error(rx: oneshot::Receiver<()>, mut server: impl Stop) { match rx.await { Ok(_) => { logger::error!("The redis server failed "); server.stop_server().await; } Err(err) => { logger::error!("Channel receiver error: {err}"); } } } #[async_trait::async_trait] pub trait Stop { async fn stop_server(&mut self); } #[async_trait::async_trait] impl Stop for ServerHandle { async fn stop_server(&mut self) { let _ = self.stop(true).await; } } #[async_trait::async_trait] impl Stop for mpsc::Sender<()> { async fn stop_server(&mut self) { let _ = self.send(()).await.map_err(|err| logger::error!("{err}")); } } pub fn get_application_builder( request_body_limit: usize, cors: settings::CorsSettings, trace_header: settings::TraceHeaderConfig, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, Config = (), Response = actix_web::dev::ServiceResponse<impl MessageBody>, Error = actix_web::Error, InitError = (), >, > { let json_cfg = actix_web::web::JsonConfig::default() .limit(request_body_limit) .content_type_required(true) .error_handler(utils::error_parser::custom_json_error_handler); actix_web::App::new() .app_data(json_cfg) .wrap(ErrorHandlers::new().handler( StatusCode::NOT_FOUND, errors::error_handlers::custom_error_handlers, )) .wrap(ErrorHandlers::new().handler( StatusCode::METHOD_NOT_ALLOWED, errors::error_handlers::custom_error_handlers, )) .wrap(middleware::default_response_headers()) .wrap(cors::cors(cors)) // this middleware works only for Http1.1 requests .wrap(middleware::Http400RequestDetailsLogger) .wrap(middleware::AddAcceptLanguageHeader) .wrap(middleware::RequestResponseMetrics) .wrap(middleware::LogSpanInitializer) .wrap(router_env::tracing_actix_web::TracingLogger::< router_env::CustomRootSpanBuilder, >::new()) .wrap( router_env::RequestIdentifier::new(&trace_header.header_name) .use_incoming_id(trace_header.id_reuse_strategy), ) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/connector.rs
crates/router/src/connector.rs
pub mod utils; #[cfg(feature = "dummy_connector")] pub use hyperswitch_connectors::connectors::DummyConnector; pub use hyperswitch_connectors::connectors::{ aci, aci::Aci, adyen, adyen::Adyen, adyenplatform, adyenplatform::Adyenplatform, affirm, affirm::Affirm, airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, archipel, archipel::Archipel, authipay, authipay::Authipay, authorizedotnet, authorizedotnet::Authorizedotnet, bambora, bambora::Bambora, bamboraapac, bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, barclaycard, barclaycard::Barclaycard, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, blackhawknetwork, blackhawknetwork::Blackhawknetwork, bluesnap, bluesnap::Bluesnap, boku, boku::Boku, braintree, braintree::Braintree, breadpay, breadpay::Breadpay, calida, calida::Calida, cashtocode, cashtocode::Cashtocode, celero, celero::Celero, chargebee, chargebee::Chargebee, checkbook, checkbook::Checkbook, checkout, checkout::Checkout, coinbase, coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, ctp_mastercard::CtpMastercard, custombilling, custombilling::Custombilling, cybersource, cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, dwolla, dwolla::Dwolla, ebanx, ebanx::Ebanx, elavon, elavon::Elavon, envoy, envoy::Envoy, facilitapay, facilitapay::Facilitapay, finix, finix::Finix, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, flexiti, flexiti::Flexiti, forte, forte::Forte, getnet, getnet::Getnet, gigadat, gigadat::Gigadat, globalpay, globalpay::Globalpay, globepay, globepay::Globepay, gocardless, gocardless::Gocardless, gpayments, gpayments::Gpayments, helcim, helcim::Helcim, hipay, hipay::Hipay, hyperswitch_vault, hyperswitch_vault::HyperswitchVault, hyperwallet, hyperwallet::Hyperwallet, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, katapult, katapult::Katapult, klarna, klarna::Klarna, loonio, loonio::Loonio, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, mpgs, mpgs::Mpgs, multisafepay, multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payjustnow, payjustnow::Payjustnow, payjustnowinstore, payjustnowinstore::Payjustnowinstore, payload, payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, peachpayments, peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, tesouro::Tesouro, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, worldpayvantiv::Worldpayvantiv, worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zift, zift::Zift, zsl, zsl::Zsl, };
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core.rs
crates/router/src/core.rs
pub mod admin; pub mod api_keys; pub mod api_locking; #[cfg(feature = "v1")] pub mod apple_pay_certificates_migration; pub mod authentication; #[cfg(feature = "v1")] pub mod blocklist; pub mod cache; pub mod card_testing_guard; pub mod cards_info; pub mod chat; pub mod conditional_config; pub mod configs; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod connector_validation; #[cfg(any(feature = "olap", feature = "oltp"))] pub mod currency; pub mod customers; #[cfg(feature = "v1")] pub mod debit_routing; pub mod disputes; pub mod encryption; pub mod errors; pub mod external_service_auth; pub mod files; #[cfg(feature = "frm")] pub mod fraud_check; pub mod gsm; pub mod health_check; #[cfg(feature = "v1")] pub mod locker_migration; pub mod mandate; pub mod metrics; pub mod payment_link; #[cfg(feature = "v2")] pub mod payment_method_balance; pub mod payment_methods; pub mod payments; #[cfg(feature = "v2")] pub mod split_payments; #[cfg(feature = "payouts")] pub mod payout_link; #[cfg(feature = "payouts")] pub mod payouts; pub mod pm_auth; pub mod poll; pub mod profile_acquirer; #[cfg(feature = "v2")] pub mod proxy; #[cfg(feature = "recon")] pub mod recon; #[cfg(feature = "v1")] pub mod refunds; #[cfg(feature = "v2")] pub mod refunds_v2; pub mod relay; #[cfg(feature = "v2")] pub mod revenue_recovery; #[cfg(feature = "v2")] pub mod revenue_recovery_data_backfill; pub mod routing; pub mod surcharge_decision_config; pub mod three_ds_decision_rule; pub mod tokenization; pub mod unified_authentication_service; pub mod unified_connector_service; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; pub mod utils; #[cfg(feature = "olap")] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; pub mod webhooks;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/env.rs
crates/router/src/env.rs
#[doc(inline)] pub use router_env::*;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows.rs
crates/router/src/workflows.rs
#[cfg(feature = "email")] pub mod api_key_expiry; #[cfg(feature = "payouts")] pub mod attach_payout_account_workflow; pub mod outgoing_webhook_retry; pub mod payment_method_status_update; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; pub mod revenue_recovery; pub mod process_dispute; pub mod dispute_list; pub mod invoice_sync;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/middleware.rs
crates/router/src/middleware.rs
use common_utils::consts::TENANT_HEADER; use futures::StreamExt; // Re-export RequestId from router_env for convenience pub use router_env::RequestId; use router_env::{ logger, tracing::{field::Empty, Instrument}, }; use crate::{headers, routes::metrics}; /// Middleware for attaching default response headers. Headers with the same key already set in a /// response will not be overwritten. pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders { use actix_web::http::header; let default_headers_middleware = actix_web::middleware::DefaultHeaders::new(); #[cfg(feature = "vergen")] let default_headers_middleware = default_headers_middleware.add(("x-hyperswitch-version", router_env::git_tag!())); default_headers_middleware // Max age of 1 year in seconds, equal to `60 * 60 * 24 * 365` seconds. .add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000")) .add((header::VIA, "HyperSwitch")) } /// Middleware to build a TOP level domain span for each request. pub struct LogSpanInitializer; impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for LogSpanInitializer where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = LogSpanInitializerMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(LogSpanInitializerMiddleware { service })) } } pub struct LogSpanInitializerMiddleware<S> { service: S, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for LogSpanInitializerMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); // TODO: have a common source of truth for the list of top level fields // /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { let tenant_id = req .headers() .get(TENANT_HEADER) .and_then(|i| i.to_str().ok()) .map(|s| s.to_owned()); let response_fut = self.service.call(req); let tenant_id_clone = tenant_id.clone(); Box::pin( async move { if let Some(tenant) = tenant_id_clone { router_env::tracing::Span::current().record("tenant_id", tenant); } let response = response_fut.await; router_env::tracing::Span::current().record("golden_log_line", true); response } .instrument( router_env::tracing::info_span!( "ROOT_SPAN", payment_id = Empty, merchant_id = Empty, connector_name = Empty, payment_method = Empty, status_code = Empty, flow = "UNKNOWN", golden_log_line = Empty, tenant_id = &tenant_id ) .or_current(), ), ) } } fn get_request_details_from_value(json_value: &serde_json::Value, parent_key: &str) -> String { match json_value { serde_json::Value::Null => format!("{parent_key}: null"), serde_json::Value::Bool(b) => format!("{parent_key}: {b}"), serde_json::Value::Number(num) => format!("{}: {}", parent_key, num.to_string().len()), serde_json::Value::String(s) => format!("{}: {}", parent_key, s.len()), serde_json::Value::Array(arr) => { let mut result = String::new(); for (index, value) in arr.iter().enumerate() { let child_key = format!("{parent_key}[{index}]"); result.push_str(&get_request_details_from_value(value, &child_key)); if index < arr.len() - 1 { result.push_str(", "); } } result } serde_json::Value::Object(obj) => { let mut result = String::new(); for (index, (key, value)) in obj.iter().enumerate() { let child_key = format!("{parent_key}[{key}]"); result.push_str(&get_request_details_from_value(value, &child_key)); if index < obj.len() - 1 { result.push_str(", "); } } result } } } /// Middleware for Logging request_details of HTTP 400 Bad Requests pub struct Http400RequestDetailsLogger; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for Http400RequestDetailsLogger where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = Http400RequestDetailsLoggerMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(Http400RequestDetailsLoggerMiddleware { service: std::rc::Rc::new(service), })) } } pub struct Http400RequestDetailsLoggerMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for Http400RequestDetailsLoggerMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future { let svc = self.service.clone(); let request_id_fut = req.extract::<RequestId>(); Box::pin(async move { let (http_req, payload) = req.into_parts(); let result_payload: Vec<Result<bytes::Bytes, actix_web::error::PayloadError>> = payload.collect().await; let payload = result_payload .into_iter() .collect::<Result<Vec<bytes::Bytes>, actix_web::error::PayloadError>>()?; let bytes = payload.clone().concat().to_vec(); let bytes_length = bytes.len(); // we are creating h1 payload manually from bytes, currently there's no way to create http2 payload with actix let (_, mut new_payload) = actix_http::h1::Payload::create(true); new_payload.unread_data(bytes.to_vec().clone().into()); let new_req = actix_web::dev::ServiceRequest::from_parts(http_req, new_payload.into()); let content_length_header = new_req .headers() .get(headers::CONTENT_LENGTH) .map(ToOwned::to_owned); let response_fut = svc.call(new_req); let response = response_fut.await?; // Log the request_details when we receive 400 status from the application if response.status() == 400 { let request_id = request_id_fut.await?.to_string(); let content_length_header_string = content_length_header .map(|content_length_header| { content_length_header.to_str().map(ToOwned::to_owned) }) .transpose() .inspect_err(|error| { logger::warn!("Could not convert content length to string {error:?}"); }) .ok() .flatten(); logger::info!("Content length from header: {content_length_header_string:?}, Bytes length: {bytes_length}"); if !bytes.is_empty() { let value_result: Result<serde_json::Value, serde_json::Error> = serde_json::from_slice(&bytes); match value_result { Ok(value) => { logger::info!( "request_id: {request_id}, request_details: {}", get_request_details_from_value(&value, "") ); } Err(err) => { logger::warn!("error while parsing the request in json value: {err}"); } } } else { logger::info!("request_id: {request_id}, request_details: Empty Body"); } } Ok(response) }) } } /// Middleware for Adding Accept-Language header based on query params pub struct AddAcceptLanguageHeader; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for AddAcceptLanguageHeader where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = AddAcceptLanguageHeaderMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(AddAcceptLanguageHeaderMiddleware { service: std::rc::Rc::new(service), })) } } pub struct AddAcceptLanguageHeaderMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for AddAcceptLanguageHeaderMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future { let svc = self.service.clone(); Box::pin(async move { #[derive(serde::Deserialize)] struct LocaleQueryParam { locale: Option<String>, } let query_params = req.query_string(); let locale_param = serde_qs::from_str::<LocaleQueryParam>(query_params).map_err(|error| { actix_web::error::ErrorBadRequest(format!( "Could not convert query params to locale query parmas: {error:?}", )) })?; let accept_language_header = req.headers().get(http::header::ACCEPT_LANGUAGE); if let Some(locale) = locale_param.locale { req.headers_mut().insert( http::header::ACCEPT_LANGUAGE, http::HeaderValue::from_str(&locale)?, ); } else if accept_language_header.is_none() { req.headers_mut().insert( http::header::ACCEPT_LANGUAGE, http::HeaderValue::from_static("en"), ); } let response_fut = svc.call(req); let response = response_fut.await?; Ok(response) }) } } /// Middleware for recording request-response metrics pub struct RequestResponseMetrics; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestResponseMetrics where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = RequestResponseMetricsMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(RequestResponseMetricsMiddleware { service: std::rc::Rc::new(service), })) } } pub struct RequestResponseMetricsMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestResponseMetricsMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { use std::borrow::Cow; let svc = self.service.clone(); let request_path = req .match_pattern() .map(Cow::<'static, str>::from) .unwrap_or_else(|| "UNKNOWN".into()); let request_method = Cow::<'static, str>::from(req.method().as_str().to_owned()); Box::pin(async move { let mut attributes = router_env::metric_attributes!(("path", request_path), ("method", request_method)) .to_vec(); let response_fut = svc.call(req); metrics::REQUESTS_RECEIVED.add(1, &attributes); let (response_result, request_duration) = common_utils::metrics::utils::time_future(response_fut).await; let response = response_result?; attributes.extend_from_slice(router_env::metric_attributes!(( "status_code", i64::from(response.status().as_u16()) ))); metrics::REQUEST_TIME.record(request_duration.as_secs_f64(), &attributes); Ok(response) }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/connection.rs
crates/router/src/connection.rs
use bb8::PooledConnection; use diesel::PgConnection; use error_stack::ResultExt; use storage_impl::errors as storage_errors; use crate::errors; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; /// Creates a Redis connection pool for the specified Redis settings /// # Panics /// /// Panics if failed to create a redis pool #[allow(clippy::expect_used)] pub async fn redis_connection( conf: &crate::configs::Settings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(&conf.redis) .await .expect("Failed to create Redis Connection Pool") } pub async fn pg_connection_read<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_accounts_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/cors.rs
crates/router/src/cors.rs
// use actix_web::http::header; use crate::configs::settings; pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors { let allowed_methods = config.allowed_methods.iter().map(|s| s.as_str()); let mut cors = actix_cors::Cors::default() .allowed_methods(allowed_methods) .allow_any_header() .expose_any_header() .max_age(config.max_age); if config.wildcard_origin { cors = cors.allow_any_origin() } else { for origin in &config.origins { cors = cors.allowed_origin(origin); } // Only allow this in case if it's not wildcard origins. ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials cors = cors.supports_credentials(); } cors }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types.rs
crates/router/src/types.rs
// FIXME: Why were these data types grouped this way? // // Folder `types` is strange for Rust ecosystem, nevertheless it might be okay. // But folder `enum` is even more strange I unlikely okay. Why should not we introduce folders `type`, `structs` and `traits`? :) // Is it better to split data types according to business logic instead. // For example, customers/address/dispute/mandate is "models". // Separation of concerns instead of separation of forms. pub mod api; pub mod authentication; pub mod connector_transformers; pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; pub mod payment_methods; pub mod pm_auth; use masking::Secret; pub mod storage; pub mod transformers; use std::marker::PhantomData; pub use api_models::{enums::Connector, mandates}; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(feature = "v2")] use common_utils::errors::CustomResult; pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit}; #[cfg(feature = "v2")] use error_stack::ResultExt; #[cfg(feature = "frm")] pub use hyperswitch_domain_models::router_data_v2::FrmFlowData; use hyperswitch_domain_models::router_flow_types::{ self, access_token_auth::AccessTokenAuth, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, IncrementalAuthorization, InitPayment, PSync, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, }; pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ AccessToken, AccessTokenAuthenticationResponse, AdditionalPaymentMethodConnectorResponse, BillingDetails, ConnectorAuthType, ConnectorResponseData, CustomerInfo, ErrorResponse, GooglePayPaymentMethodDetails, GooglePayPredecryptDataInternal, L2L3Data, OrderInfo, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData, TaxInfo, }, router_data_v2::{ AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RouterDataV2, UasFlowData, WebhookSourceVerifyData, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions, CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund, DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData, PreprocessingResponseId, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, VerifyWebhookStatus, }, }; #[cfg(feature = "payouts")] pub use hyperswitch_domain_models::{ router_data_v2::PayoutFlowData, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType, PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType, }; pub use hyperswitch_interfaces::{ disputes::DisputePayload, types::{ AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, FetchDisputesType, IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostCaptureVoidType, PaymentsPostProcessingType, PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, PaymentsUpdateMetadataType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType, }, }; #[cfg(feature = "v2")] use crate::core::errors; pub use crate::core::payments::CustomerDetails; use crate::{ consts, core::payments::{OperationSessionGetters, PaymentData}, services, types::transformers::{ForeignFrom, ForeignTryFrom}, }; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPostProcessingRouterData = RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsInitRouterData = RouterData<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsBalanceRouterData = RouterData<Balance, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type PaymentsExtendAuthorizationRouterData = RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData< router_flow_types::PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, >; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsResponseRouterData<R> = ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureResponseRouterData<R> = ResponseRouterData<PostCaptureVoid, R, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsExtendAuthorizationResponseRouterData<R> = ResponseRouterData< ExtendAuthorization, R, PaymentsExtendAuthorizationData, PaymentsResponseData, >; pub type PaymentsBalanceResponseRouterData<R> = ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsInitResponseRouterData<R> = ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type SdkSessionUpdateResponseRouterData<R> = ResponseRouterData<SdkSessionUpdate, R, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsPreprocessingResponseRouterData<R> = ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; pub type TokenizationResponseRouterData<R> = ResponseRouterData<PaymentMethodToken, R, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerResponseRouterData<R> = ResponseRouterData<CreateConnectorCustomer, R, ConnectorCustomerData, PaymentsResponseData>; pub type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type AcceptDisputeRouterData = RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; pub type SubmitEvidenceRouterData = RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; pub type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>; pub type RetrieveFileRouterData = RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; pub type DefendDisputeRouterData = RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; pub type FetchDisputesRouterData = RouterData<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; pub type DisputeSyncRouterData = RouterData<Dsync, DisputeSyncData, DisputeSyncResponse>; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutActionData = Vec<( storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, Option<api_models::payments::Address>, )>; #[cfg(feature = "payouts")] pub trait PayoutIndividualDetailsExt { type Error; fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; } pub trait Capturable { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { None } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _get_amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { None } } #[cfg(feature = "v1")] impl Capturable for PaymentsAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data.get_capture_method().unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndProcessing | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } #[cfg(feature = "v1")] impl Capturable for PaymentsCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { Some(self.amount_to_capture) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCapturedAndProcessing | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } #[cfg(feature = "v1")] impl Capturable for CompleteAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data .get_capture_method() .unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } impl Capturable for SetupMandateRequestData {} impl Capturable for PaymentsTaxCalculationData {} impl Capturable for SdkPaymentsSessionUpdateData {} impl Capturable for PaymentsPostSessionTokensData {} impl Capturable for PaymentsUpdateMetadataData {} impl Capturable for PaymentsCancelData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None, } } } impl Capturable for PaymentsCancelPostCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCapturedAndProcessing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } impl Capturable for PaymentsApproveData {} impl Capturable for PaymentsRejectData {} impl Capturable for PaymentsSessionData {} impl Capturable for PaymentsIncrementalAuthorizationData { fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { amount_capturable.or(Some(self.total_amount)) } } impl Capturable for PaymentsSyncData { #[cfg(feature = "v1")] fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { payment_data .payment_attempt .amount_to_capture .or(payment_data.payment_intent.amount_captured) .or(amount_captured.map(MinorUnit::new)) .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v2")] fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // TODO: add a getter for this payment_data .payment_attempt .amount_details .get_amount_to_capture() .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v1")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { amount_capturable.or(Some(MinorUnit::get_amount_as_i64( payment_data.payment_attempt.amount_capturable, ))) } } #[cfg(feature = "v2")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { None } } } impl Capturable for PaymentsExtendAuthorizationData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired | common_enums::IntentStatus::Succeeded => Some(0), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCapturedAndProcessing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } pub struct AddAccessTokenResult { pub access_token_result: Result<Option<AccessToken>, ErrorResponse>, pub connector_supports_access_token: bool, } pub struct PaymentMethodTokenResult { pub payment_method_token_result: Result<Option<String>, ErrorResponse>, pub is_payment_method_tokenization_performed: bool, pub connector_response: Option<ConnectorResponseData>, } #[derive(Clone)] pub struct CreateOrderResult { pub create_order_result: Result<String, ErrorResponse>, pub should_continue_further: bool, } pub struct PspTokenResult { pub token: Result<String, ErrorResponse>, } /// Data extracted from UCS response pub struct UcsAuthorizeResponseData { pub router_data_response: Result<(PaymentsResponseData, common_enums::AttemptStatus), ErrorResponse>, pub status_code: u16, pub connector_customer_id: Option<String>, pub connector_response: Option<ConnectorResponseData>, } pub struct UcsRepeatPaymentResponseData { pub router_data_response: Result<(PaymentsResponseData, common_enums::AttemptStatus), ErrorResponse>, pub status_code: u16, pub connector_customer_id: Option<String>, pub connector_response: Option<ConnectorResponseData>, } pub struct UcsSetupMandateResponseData { pub router_data_response: Result<(PaymentsResponseData, common_enums::AttemptStatus), ErrorResponse>, pub status_code: u16, pub connector_customer_id: Option<String>, pub connector_response: Option<ConnectorResponseData>, } #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect, NoRedirect, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PollConfig { pub delay_in_secs: i8, pub frequency: i8, } impl PollConfig { pub fn get_poll_config_key(connector: String) -> String { format!("poll_config_external_three_ds_{connector}") } } impl Default for PollConfig { fn default() -> Self { Self { delay_in_secs: consts::DEFAULT_POLL_DELAY_IN_SECS, frequency: consts::DEFAULT_POLL_FREQUENCY, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub business_profile: domain::Profile, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse<D> { pub payment_data: D, pub profile: domain::Profile, } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct AuthenticatePaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub poll_config: PollConfig, pub business_profile: domain::Profile, } #[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct ConnectorResponse { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, pub payment_id: common_utils::id_type::PaymentId, pub amount: i64, pub connector_transaction_id: String, pub return_url: Option<String>, pub three_ds_form: Option<services::RedirectForm>, } pub struct ResponseRouterData<Flow, R, Request, Response> { pub response: R, pub data: RouterData<Flow, Request, Response>, pub http_code: u16, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub enum RecipientIdType { ConnectorId(Secret<String>), LockerId(Secret<String>), }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils.rs
crates/router/src/utils.rs
pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; pub mod db_utils; pub mod ext_traits; #[cfg(feature = "kv_store")] pub mod storage_partitioning; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; #[cfg(feature = "olap")] pub mod verify_connector; use std::fmt::Debug; use api_models::{ enums, payments::{self}, subscription as subscription_types, webhooks, }; pub use common_utils::{ crypto::{self, Encryptable}, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, id_type, pii, validation::validate_email, }; #[cfg(feature = "v1")] use common_utils::{ type_name, types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::ResultExt; pub use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v1")] use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, SwitchStrategy}; use nanoid::nanoid; use serde::de::DeserializeOwned; use serde_json::Value; #[cfg(feature = "v1")] use subscriptions::{subscription_handler::SubscriptionHandler, workflows::InvoiceSyncHandler}; use tracing_futures::Instrument; pub use self::ext_traits::{OptionExt, ValidateCall}; use crate::{ consts, core::{ authentication::types::ExternalThreeDSConnectorMetadata, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments as payments_core, }, headers::ACCEPT_LANGUAGE, logger, routes::{metrics, SessionState}, services::{self, authentication::get_header_value_by_key}, types::{self, domain, transformers::ForeignInto}, }; #[cfg(feature = "v1")] use crate::{core::webhooks as webhooks_core, types::storage}; pub mod error_parser { use std::fmt::Display; use actix_web::{ error::{Error, JsonPayloadError}, http::StatusCode, HttpRequest, ResponseError, }; #[derive(Debug)] struct CustomJsonError { err: JsonPayloadError, } // Display is a requirement defined by the actix crate for implementing ResponseError trait impl Display for CustomJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( serde_json::to_string(&serde_json::json!({ "error": { "error_type": "invalid_request", "message": self.err.to_string(), "code": "IR_06", } })) .as_deref() .unwrap_or("Invalid Json Error"), ) } } impl ResponseError for CustomJsonError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { Error::from(CustomJsonError { err }) } } #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS)) } pub trait ConnectorResponseExt: Sized { fn get_response(self) -> RouterResult<types::Response>; fn get_error_response(self) -> RouterResult<types::Response>; fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> { self.get_response()? .response .parse_struct(type_name) .change_context(errors::ApiErrorResponse::InternalServerError) } } impl<E> ConnectorResponseExt for Result<Result<types::Response, types::Response>, error_stack::Report<E>> { fn get_error_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Ok(res) => { logger::error!(response=?res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting error response, received response: {res:?}" )) } Err(err_res) => Ok(err_res), }) } fn get_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { logger::error!(error_response=?err_res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting response, received error response: {err_res:?}" )) } Ok(res) => Ok(res), }) } } #[inline] pub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String { format!("{payout_id}_{attempt_count}") } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_payment_id_type( state: &SessionState, payment_id_type: payments::PaymentIdType, platform: &domain::Platform, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( &payment_id, platform.get_processor().get_account().get_id(), platform.get_processor().get_key_store(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound), payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => { let attempt = db .find_payment_attempt_by_merchant_id_connector_txn_id( platform.get_processor().get_account().get_id(), &connector_transaction_id, platform.get_processor().get_account().storage_scheme, platform.get_processor().get_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &attempt.payment_id, platform.get_processor().get_account().get_id(), platform.get_processor().get_key_store(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PaymentAttemptId(attempt_id) => { let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &attempt_id, platform.get_processor().get_account().get_id(), platform.get_processor().get_account().storage_scheme, platform.get_processor().get_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &attempt.payment_id, platform.get_processor().get_account().get_id(), platform.get_processor().get_key_store(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PreprocessingId(_) => { Err(errors::ApiErrorResponse::PaymentNotFound)? } } } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_refund_id_type( state: &SessionState, refund_id_type: webhooks::RefundIdType, platform: &domain::Platform, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( platform.get_processor().get_account().get_id(), &id, platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( platform.get_processor().get_account().get_id(), &id, connector_name, platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, }; let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &refund.attempt_id, platform.get_processor().get_account().get_id(), platform.get_processor().get_account().storage_scheme, platform.get_processor().get_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &attempt.payment_id, platform.get_processor().get_account().get_id(), platform.get_processor().get_key_store(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_mandate_id_type( state: &SessionState, mandate_id_type: webhooks::MandateIdType, platform: &domain::Platform, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( platform.get_processor().get_account().get_id(), mandate_id.as_str(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db .find_mandate_by_merchant_id_connector_mandate_id( platform.get_processor().get_account().get_id(), connector_mandate_id.as_str(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("original_payment_id not present in mandate record")?, platform.get_processor().get_account().get_id(), platform.get_processor().get_key_store(), platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_mca_from_authentication_id_type( state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, platform: &domain::Platform, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( platform.get_processor().get_account().get_id(), &authentication_id, platform.get_processor().get_key_store(), &state.into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?, webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => { db.find_authentication_by_merchant_id_connector_authentication_id( platform.get_processor().get_account().get_id().clone(), connector_authentication_id, platform.get_processor().get_key_store(), &state.into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? } }; #[cfg(feature = "v1")] { // raise error if merchant_connector_id is not present since it should we be present in the current flow let mca_id = authentication .merchant_connector_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("merchant_connector_id not present in authentication record")?; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( platform.get_processor().get_account().get_id(), &mca_id, platform.get_processor().get_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] //get mca using id { let _ = key_store; let _ = authentication; todo!() } } #[cfg(feature = "v1")] pub async fn get_mca_from_payment_intent( state: &SessionState, platform: &domain::Platform, payment_intent: PaymentIntent, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; #[cfg(feature = "v1")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), platform.get_processor().get_account().get_id(), platform.get_processor().get_account().storage_scheme, platform.get_processor().get_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( key_manager_state, key_store, &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( platform.get_processor().get_account().get_id(), &merchant_connector_id, platform.get_processor().get_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = key_store; let _ = key_manager_state; let _ = connector_name; todo!() } } None => { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( &profile_id, connector_name, platform.get_processor().get_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { //get mca using id let _ = profile_id; todo!() } } } } #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( state: &SessionState, platform: &domain::Platform, payout_id_type: webhooks::PayoutIdType, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( platform.get_processor().get_account().get_id(), &payout_attempt_id, platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db .find_payout_attempt_by_merchant_id_connector_payout_id( platform.get_processor().get_account().get_id(), &connector_payout_id, platform.get_processor().get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; match payout.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( platform.get_processor().get_account().get_id(), &merchant_connector_id, platform.get_processor().get_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = platform.get_processor().get_key_store(); let _ = connector_name; todo!() } } None => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( &payout.profile_id, connector_name, platform.get_processor().get_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {}", payout.profile_id.get_string_repr(), connector_name ), }, ) } #[cfg(feature = "v2")] { todo!() } } } } #[cfg(feature = "v1")] pub async fn get_mca_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, platform: &domain::Platform, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; #[cfg(feature = "v1")] let default_profile_id = platform .get_processor() .get_account() .default_profile .as_ref(); #[cfg(feature = "v2")] let default_profile_id = Option::<&String>::None; match default_profile_id { Some(profile_id) => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( profile_id, connector_name, platform.get_processor().get_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { let _db = db; let _profile_id = profile_id; todo!() } } _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( state, platform, find_payment_intent_from_payment_id_type(state, payment_id_type, platform) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( state, platform, find_payment_intent_from_refund_id_type( state, refund_id_type, platform, connector_name, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( state, platform, find_payment_intent_from_mandate_id_type(state, mandate_id_type, platform) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type(state, authentication_id_type, platform).await } webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => { #[cfg(feature = "v1")] { let subscription_state = state.clone().into(); let subscription_handler = SubscriptionHandler::new(&subscription_state, platform); let mut subscription_with_handler = subscription_handler .find_subscription(subscription_id_type) .await?; subscription_with_handler.get_mca(connector_name).await } #[cfg(feature = "v2")] { let _db = db; todo!() } } #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt(state, platform, payout_id_type, connector_name).await } }, } } // validate json format for the error pub fn handle_json_response_deserialization_failure( res: types::Response, connector: &'static str, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE .add(1, router_env::metric_attributes!(("connector", connector))); let response_data = String::from_utf8(res.response.to_vec()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; // check for whether the response is in json format match serde_json::from_str::<Value>(&response_data) { // in case of unexpected response but in json format Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?, // in case of unexpected response but in html or string format Err(error_msg) => { logger::error!(deserialization_error=?error_msg); logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data); Ok(types::ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: Some(response_data), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } } pub fn get_http_status_code_type( status_code: u16, ) -> CustomResult<String, errors::ApiErrorResponse> { let status_code_type = match status_code { 100..=199 => "1xx", 200..=299 => "2xx", 300..=399 => "3xx", 400..=499 => "4xx", 500..=599 => "5xx", _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid http status code")?, }; Ok(status_code_type.to_string()) } pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { if let Some(status_code) = option_status_code { let status_code_type = get_http_status_code_type(status_code).ok(); match status_code_type.as_deref() { Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]), Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]), Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]), Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]), Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]), _ => logger::info!("Skip metrics as invalid http status code received from connector"), }; } else { logger::info!("Skip metrics as no http status code received from connector") } } #[cfg(feature = "v1")] #[async_trait::async_trait] pub trait CustomerAddress { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address =
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/macros.rs
crates/router/src/macros.rs
pub use common_utils::newtype; #[macro_export] macro_rules! get_payment_link_config_value_based_on_priority { ($config:expr, $business_config:expr, $field:ident, $default:expr) => { $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| business_config.$field.clone()) }) .unwrap_or($default) }; } #[macro_export] macro_rules! get_payment_link_config_value { ($config:expr, $business_config:expr, $(($field:ident, $default:expr)),*) => { ( $(get_payment_link_config_value_based_on_priority!($config, $business_config, $field, $default)),* ) }; ($config:expr, $business_config:expr, $(($field:ident)),*) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| business_config.$field.clone()) }) ),* ) }; ($config:expr, $business_config:expr, $(($field:ident $(, $transform:expr)?)),* $(,)?) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| { let value = business_config.$field.clone(); $(let value = value.map($transform);)? value }) }) ),* ) }; }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/analytics_validator.rs
crates/router/src/analytics_validator.rs
use analytics::errors::AnalyticsError; use api_models::analytics::AnalyticsRequest; use common_utils::errors::CustomResult; use currency_conversion::types::ExchangeRates; use router_env::logger; use crate::core::currency::get_forex_exchange_rates; pub async fn request_validator( req_type: AnalyticsRequest, state: &crate::routes::SessionState, ) -> CustomResult<Option<ExchangeRates>, AnalyticsError> { let forex_enabled = state.conf.analytics.get_inner().get_forex_enabled(); let require_forex_functionality = req_type.requires_forex_functionality(); let ex_rates = if forex_enabled && require_forex_functionality { logger::info!("Fetching forex exchange rates"); Some(get_forex_exchange_rates(state.clone()).await?) } else { None }; Ok(ex_rates) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events.rs
crates/router/src/events.rs
use std::collections::HashMap; use common_utils::types::TenantConfig; use error_stack::ResultExt; use events::{EventsError, Message, MessagingInterface}; use hyperswitch_interfaces::events as events_interfaces; use masking::ErasedMaskSerialize; use router_env::logger; use serde::{Deserialize, Serialize}; use storage_impl::errors::{ApplicationError, StorageError, StorageResult}; use time::PrimitiveDateTime; use crate::{ db::KafkaProducer, services::kafka::{KafkaMessage, KafkaSettings}, }; pub mod api_logs; pub mod audit_events; pub mod connector_api_logs; pub mod event_logger; pub mod outgoing_webhook_logs; pub mod routing_api_logs; #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum EventType { PaymentIntent, FraudCheck, PaymentAttempt, Refund, ApiLogs, ConnectorApiLogs, OutgoingWebhookLogs, Dispute, AuditEvent, #[cfg(feature = "payouts")] Payout, Consolidated, Authentication, RoutingApiLogs, RevenueRecovery, } #[derive(Debug, Default, Deserialize, Clone)] #[serde(tag = "source")] #[serde(rename_all = "lowercase")] pub enum EventsConfig { Kafka { kafka: Box<KafkaSettings>, }, #[default] Logs, } #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone)] pub enum EventsHandler { Kafka(KafkaProducer), Logs(event_logger::EventLogger), } impl Default for EventsHandler { fn default() -> Self { Self::Logs(event_logger::EventLogger {}) } } impl events_interfaces::EventHandlerInterface for EventsHandler { fn log_connector_event(&self, event: &events_interfaces::connector_api_logs::ConnectorEvent) { self.log_event(event); } } impl EventsConfig { pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> { Ok(match self { Self::Kafka { kafka } => EventsHandler::Kafka( KafkaProducer::create(kafka) .await .change_context(StorageError::InitializationError)?, ), Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()), }) } pub fn validate(&self) -> Result<(), ApplicationError> { match self { Self::Kafka { kafka } => kafka.validate(), Self::Logs => Ok(()), } } } impl EventsHandler { pub fn log_event<T: KafkaMessage>(&self, event: &T) { match self { Self::Kafka(kafka) => kafka.log_event(event).unwrap_or_else(|e| { logger::error!("Failed to log event: {:?}", e); }), Self::Logs(logger) => logger.log_event(event), }; } pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) { if let Self::Kafka(kafka_producer) = self { kafka_producer.set_tenancy(tenant_config); } } } impl MessagingInterface for EventsHandler { type MessageClass = EventType; fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, { match self { Self::Kafka(a) => a.send_message(data, metadata, timestamp), Self::Logs(a) => a.send_message(data, metadata, timestamp), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false