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/common_utils/src/lib.rs
crates/common_utils/src/lib.rs
#![warn(missing_docs, missing_debug_implementations)] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] use masking::{ExposeInterface, PeekInterface, Secret}; pub mod access_token; pub mod consts; pub mod crypto; pub mod custom_serde; #[allow(missing_docs)] // Todo: add docs pub mod encryption; pub mod errors; #[allow(missing_docs)] // Todo: add docs pub mod events; pub mod ext_traits; pub mod fp_utils; /// Used for hashing pub mod hashing; pub mod id_type; #[cfg(feature = "keymanager")] pub mod keymanager; pub mod link_utils; pub mod macros; #[cfg(feature = "metrics")] pub mod metrics; pub mod new_type; pub mod payout_method_utils; pub mod pii; #[allow(missing_docs)] // Todo: add docs pub mod request; #[cfg(feature = "signals")] pub mod signals; pub mod transformers; pub mod types; /// Unified Connector Service (UCS) interface definitions. /// /// This module defines types and traits for interacting with the Unified Connector Service. /// It includes reference ID types for payments and refunds, and a trait for extracting /// UCS reference information from requests. pub mod ucs_types; pub mod validation; pub use base64_serializer::Base64Serializer; /// Date-time utilities. pub mod date_time { #[cfg(feature = "async_ext")] use std::time::Instant; use std::{marker::PhantomData, num::NonZeroU8}; use masking::{Deserialize, Serialize}; use time::{ format_description::{ well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision}, BorrowedFormatItem, }, OffsetDateTime, PrimitiveDateTime, }; /// Enum to represent date formats #[derive(Debug)] pub enum DateFormat { /// Format the date in 20191105081132 format YYYYMMDDHHmmss, /// Format the date in 20191105 format YYYYMMDD, /// Format the date in 201911050811 format YYYYMMDDHHmm, /// Format the date in 05112019081132 format DDMMYYYYHHmmss, } /// Create a new [`PrimitiveDateTime`] with the current date and time in UTC. pub fn now() -> PrimitiveDateTime { let utc_date_time = OffsetDateTime::now_utc(); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) } /// Convert from OffsetDateTime to PrimitiveDateTime pub fn convert_to_pdt(offset_time: OffsetDateTime) -> PrimitiveDateTime { PrimitiveDateTime::new(offset_time.date(), offset_time.time()) } /// Return the UNIX timestamp of the current date and time in UTC pub fn now_unix_timestamp() -> i64 { OffsetDateTime::now_utc().unix_timestamp() } /// Calculate execution time for a async block in milliseconds #[cfg(feature = "async_ext")] pub async fn time_it<T, Fut: futures::Future<Output = T>, F: FnOnce() -> Fut>( block: F, ) -> (T, f64) { let start = Instant::now(); let result = block().await; (result, start.elapsed().as_secs_f64() * 1000f64) } /// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132 pub fn format_date( date: PrimitiveDateTime, format: DateFormat, ) -> Result<String, time::error::Format> { let format = <&[BorrowedFormatItem<'_>]>::from(format); date.format(&format) } /// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> { const ISO_CONFIG: EncodedConfig = Config::DEFAULT .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(3), }) .encode(); now().assume_utc().format(&Iso8601::<ISO_CONFIG>) } /// Return the current date and time in UTC formatted as "ddd, DD MMM YYYY HH:mm:ss GMT". pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> { let now_utc = OffsetDateTime::now_utc(); // Desired format: ddd, DD MMM YYYY HH:mm:ss GMT // Example: Fri, 23 May 2025 06:19:35 GMT let format = time::macros::format_description!( "[weekday repr:short], [day padding:zero] [month repr:short] [year repr:full] [hour padding:zero repr:24]:[minute padding:zero]:[second padding:zero] GMT" ); now_utc.format(&format) } impl From<DateFormat> for &[BorrowedFormatItem<'_>] { fn from(format: DateFormat) -> Self { match format { DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"), DateFormat::YYYYMMDD => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero]"), DateFormat::YYYYMMDDHHmm => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero]"), DateFormat::DDMMYYYYHHmmss => time::macros::format_description!("[day padding:zero][month padding:zero repr:numerical][year repr:full][hour padding:zero repr:24][minute padding:zero][second padding:zero]"), } } } /// Format the date in 05112019 format #[derive(Debug, Clone)] pub struct DDMMYYYY; /// Format the date in 20191105 format #[derive(Debug, Clone)] pub struct YYYYMMDD; /// Format the date in 20191105081132 format #[derive(Debug, Clone)] pub struct YYYYMMDDHHmmss; /// To serialize the date in Dateformats like YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY #[derive(Debug, Deserialize, Clone)] pub struct DateTime<T: TimeStrategy> { inner: PhantomData<T>, value: PrimitiveDateTime, } impl<T: TimeStrategy> From<PrimitiveDateTime> for DateTime<T> { fn from(value: PrimitiveDateTime) -> Self { Self { inner: PhantomData, value, } } } /// Time strategy for the Date, Eg: YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY pub trait TimeStrategy { /// Stringify the date as per the Time strategy fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result; } impl<T: TimeStrategy> Serialize for DateTime<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.collect_str(self) } } impl<T: TimeStrategy> std::fmt::Display for DateTime<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { T::fmt(&self.value, f) } } impl TimeStrategy for DDMMYYYY { fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let year = input.year(); #[allow(clippy::as_conversions)] let month = input.month() as u8; let day = input.day(); let output = format!("{day:02}{month:02}{year}"); f.write_str(&output) } } impl TimeStrategy for YYYYMMDD { fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let year = input.year(); #[allow(clippy::as_conversions)] let month: u8 = input.month() as u8; let day = input.day(); let output = format!("{year}{month:02}{day:02}"); f.write_str(&output) } } impl TimeStrategy for YYYYMMDDHHmmss { fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let year = input.year(); #[allow(clippy::as_conversions)] let month = input.month() as u8; let day = input.day(); let hour = input.hour(); let minute = input.minute(); let second = input.second(); let output = format!("{year}{month:02}{day:02}{hour:02}{minute:02}{second:02}"); f.write_str(&output) } } } /// Generate a nanoid with the given prefix and length #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS)) } /// Generate a ReferenceId with the default length with the given prefix fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u8>( prefix: &str, ) -> id_type::LengthId<MAX_LENGTH, MIN_LENGTH> { id_type::LengthId::<MAX_LENGTH, MIN_LENGTH>::new(prefix) } /// Generate a customer id with default length, with prefix as `cus` pub fn generate_customer_id_of_default_length() -> id_type::CustomerId { use id_type::GenerateId; id_type::CustomerId::generate() } /// Generate a organization id with default length, with prefix as `org` pub fn generate_organization_id_of_default_length() -> id_type::OrganizationId { use id_type::GenerateId; id_type::OrganizationId::generate() } /// Generate a profile id with default length, with prefix as `pro` pub fn generate_profile_id_of_default_length() -> id_type::ProfileId { use id_type::GenerateId; id_type::ProfileId::generate() } /// Generate a routing id with default length, with prefix as `routing` pub fn generate_routing_id_of_default_length() -> id_type::RoutingId { use id_type::GenerateId; id_type::RoutingId::generate() } /// Generate a merchant_connector_account id with default length, with prefix as `mca` pub fn generate_merchant_connector_account_id_of_default_length( ) -> id_type::MerchantConnectorAccountId { use id_type::GenerateId; id_type::MerchantConnectorAccountId::generate() } /// Generate a profile_acquirer id with default length, with prefix as `mer_acq` pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcquirerId { use id_type::GenerateId; id_type::ProfileAcquirerId::generate() } /// Generate a nanoid with the given prefix and a default length #[inline] pub fn generate_id_with_default_len(prefix: &str) -> String { let len: usize = consts::ID_LENGTH; format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS)) } /// Generate a time-ordered (time-sortable) unique identifier using the current time #[inline] pub fn generate_time_ordered_id(prefix: &str) -> String { format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple()) } /// Generate a time-ordered (time-sortable) unique identifier using the current time without prefix #[inline] pub fn generate_time_ordered_id_without_prefix() -> String { uuid::Uuid::now_v7().as_simple().to_string() } /// Generate a nanoid with the specified length #[inline] pub fn generate_id_with_len(length: usize) -> String { nanoid::nanoid!(length, &consts::ALPHABETS) } #[allow(missing_docs)] pub trait DbConnectionParams { fn get_username(&self) -> &str; fn get_password(&self) -> Secret<String>; fn get_host(&self) -> &str; fn get_port(&self) -> u16; fn get_dbname(&self) -> &str; fn get_database_url(&self, schema: &str) -> String { format!( "postgres://{}:{}@{}:{}/{}?application_name={}&options=-c%20search_path%3D{}", self.get_username(), self.get_password().peek(), self.get_host(), self.get_port(), self.get_dbname(), schema, schema, ) } } // Can't add doc comments for macro invocations, neither does the macro allow it. #[allow(missing_docs)] mod base64_serializer { use base64_serde::base64_serde_type; base64_serde_type!(pub Base64Serializer, crate::consts::BASE64_ENGINE); } /// Merges two optional JSON values into a single JSON object. /// If both values are objects, their key-value pairs are merged. /// If only one value exists, it is returned. /// If neither exists, None is returned. pub fn merge_json_values( first: Option<pii::SecretSerdeValue>, second: Option<pii::SecretSerdeValue>, ) -> Option<pii::SecretSerdeValue> { match first.clone().zip(second.clone()) { Some((first, second)) => { let first_value = first.expose(); let second_value = second.expose(); match (first_value, second_value) { ( serde_json::Value::Object(mut first_map), serde_json::Value::Object(second_map), ) => { // if the first and second has the same keys then the value will be updated with that of the second first_map.extend(second_map); Some(pii::SecretSerdeValue::new(serde_json::Value::Object( first_map, ))) } // ideally both Value should of variant Object but if one of them is not an object, it follows the previous behaviour i.e pass payment method metadata (first_val, _) => Some(pii::SecretSerdeValue::new(first_val)), } } None => first.or(second), } } #[cfg(test)] mod nanoid_tests { use super::*; use crate::{ consts::{ MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH, }, id_type::AlphaNumericId, }; #[test] fn test_generate_id_with_alphanumeric_id() { let alphanumeric_id = AlphaNumericId::from(generate_id(10, "def").into()); assert!(alphanumeric_id.is_ok()) } #[test] fn test_generate_merchant_ref_id_with_default_length() { let ref_id = id_type::LengthId::< MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH, >::from(generate_id_with_default_len("def").into()); assert!(ref_id.is_ok()) } } /// Module for tokenization-related functionality /// /// This module provides types and functions for handling tokenized payment data, /// including response structures and token generation utilities. #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub mod tokenization;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/access_token.rs
crates/common_utils/src/access_token.rs
//! Commonly used utilities for access token use std::fmt::Display; use crate::id_type; /// Create a default key for fetching the access token from redis pub fn get_default_access_token_key( merchant_id: &id_type::MerchantId, merchant_connector_id_or_connector_name: impl Display, ) -> String { format!( "access_token_{}_{}", merchant_id.get_string_repr(), merchant_connector_id_or_connector_name ) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/pii.rs
crates/common_utils/src/pii.rs
//! Personal Identifiable Information protection. use std::{convert::AsRef, fmt, ops, str::FromStr}; use diesel::{ backend::Backend, deserialize, deserialize::FromSql, prelude::*, serialize::{Output, ToSql}, sql_types, AsExpression, }; use error_stack::ResultExt; use masking::{ExposeInterface, Secret, Strategy, WithType}; #[cfg(feature = "logs")] use router_env::logger; use serde::Deserialize; use crate::{ crypto::Encryptable, errors::{self, ValidationError}, validation::{validate_email, validate_phone_number}, }; /// A string constant representing a redacted or masked value. pub const REDACTED: &str = "Redacted"; /// Type alias for serde_json value which has Secret Information pub type SecretSerdeValue = Secret<serde_json::Value>; /// Strategy for masking a PhoneNumber #[derive(Debug)] pub enum PhoneNumberStrategy {} /// Phone Number #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(try_from = "String")] pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>); impl<T> Strategy<T> for PhoneNumberStrategy where T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); if let Some(val_str) = val_str.get(val_str.len() - 4..) { // masks everything but the last 4 digits write!(f, "{}{}", "*".repeat(val_str.len() - 4), val_str) } else { #[cfg(feature = "logs")] logger::error!("Invalid phone number: {val_str}"); WithType::fmt(val, f) } } } impl FromStr for PhoneNumber { type Err = error_stack::Report<ValidationError>; fn from_str(phone_number: &str) -> Result<Self, Self::Err> { validate_phone_number(phone_number)?; let secret = Secret::<String, PhoneNumberStrategy>::new(phone_number.to_string()); Ok(Self(secret)) } } impl TryFrom<String> for PhoneNumber { type Error = error_stack::Report<errors::ParsingError>; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value).change_context(errors::ParsingError::PhoneNumberParsingError) } } impl ops::Deref for PhoneNumber { type Target = Secret<String, PhoneNumberStrategy>; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for PhoneNumber { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<DB> Queryable<sql_types::Text, DB> for PhoneNumber where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for PhoneNumber where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::from_str(val.as_str())?) } } impl<DB> ToSql<sql_types::Text, DB> for PhoneNumber where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } /* /// Phone number #[derive(Debug)] pub struct PhoneNumber; impl<T> Strategy<T> for PhoneNumber where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); if val_str.len() < 10 || val_str.len() > 12 { return WithType::fmt(val, f); } write!( f, "{}{}{}", &val_str[..2], "*".repeat(val_str.len() - 5), &val_str[(val_str.len() - 3)..] ) } } */ /// Strategy for Encryption #[derive(Debug)] pub enum EncryptionStrategy {} impl<T> Strategy<T> for EncryptionStrategy where T: AsRef<[u8]>, { fn fmt(value: &T, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( fmt, "*** Encrypted data of length {} bytes ***", value.as_ref().len() ) } } /// Client secret #[derive(Debug)] pub enum ClientSecret {} impl<T> Strategy<T> for ClientSecret where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); let client_secret_segments: Vec<&str> = val_str.split('_').collect(); if client_secret_segments.len() != 4 || !client_secret_segments.contains(&"pay") || !client_secret_segments.contains(&"secret") { return WithType::fmt(val, f); } if let Some((client_secret_segments_0, client_secret_segments_1)) = client_secret_segments .first() .zip(client_secret_segments.get(1)) { write!( f, "{}_{}_{}", client_secret_segments_0, client_secret_segments_1, "*".repeat( val_str.len() - (client_secret_segments_0.len() + client_secret_segments_1.len() + 2) ) ) } else { #[cfg(feature = "logs")] logger::error!("Invalid client secret: {val_str}"); WithType::fmt(val, f) } } } /// Strategy for masking Email #[derive(Debug, Copy, Clone, Deserialize)] pub enum EmailStrategy {} impl<T> Strategy<T> for EmailStrategy where T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); match val_str.split_once('@') { Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b), None => WithType::fmt(val, f), } } } /// Email address #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression, )] #[diesel(sql_type = sql_types::Text)] #[serde(try_from = "String")] pub struct Email(Secret<String, EmailStrategy>); impl From<Encryptable<Secret<String, EmailStrategy>>> for Email { fn from(item: Encryptable<Secret<String, EmailStrategy>>) -> Self { Self(item.into_inner()) } } impl ExposeInterface<Secret<String, EmailStrategy>> for Email { fn expose(self) -> Secret<String, EmailStrategy> { self.0 } } impl TryFrom<String> for Email { type Error = error_stack::Report<errors::ParsingError>; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value).change_context(errors::ParsingError::EmailParsingError) } } impl ops::Deref for Email { type Target = Secret<String, EmailStrategy>; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for Email { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<DB> Queryable<sql_types::Text, DB> for Email where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for Email where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::from_str(val.as_str())?) } } impl<DB> ToSql<sql_types::Text, DB> for Email where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl FromStr for Email { type Err = error_stack::Report<ValidationError>; fn from_str(email: &str) -> Result<Self, Self::Err> { if email.eq(REDACTED) { return Ok(Self(Secret::new(email.to_string()))); } match validate_email(email) { Ok(_) => { let secret = Secret::<String, EmailStrategy>::new(email.to_string()); Ok(Self(secret)) } Err(_) => Err(ValidationError::InvalidValue { message: "Invalid email address format".into(), } .into()), } } } /// IP address #[derive(Debug)] pub enum IpAddress {} impl<T> Strategy<T> for IpAddress where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); let segments: Vec<&str> = val_str.split('.').collect(); if segments.len() != 4 { return WithType::fmt(val, f); } for seg in segments.iter() { if seg.is_empty() || seg.len() > 3 { return WithType::fmt(val, f); } } if let Some(segments) = segments.first() { write!(f, "{segments}.**.**.**") } else { #[cfg(feature = "logs")] logger::error!("Invalid IP address: {val_str}"); WithType::fmt(val, f) } } } /// Strategy for masking UPI VPA's #[derive(Debug)] pub enum UpiVpaMaskingStrategy {} impl<T> Strategy<T> for UpiVpaMaskingStrategy where T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let vpa_str: &str = val.as_ref(); if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') { let masked_user_identifier = "*".repeat(user_identifier.len()); write!(f, "{masked_user_identifier}@{bank_or_psp}") } else { WithType::fmt(val, f) } } } #[cfg(test)] mod pii_masking_strategy_tests { use std::str::FromStr; use masking::{ExposeInterface, Secret}; use super::{ClientSecret, Email, IpAddress, UpiVpaMaskingStrategy}; use crate::pii::{EmailStrategy, REDACTED}; /* #[test] fn test_valid_phone_number_masking() { let secret: Secret<String, PhoneNumber> = Secret::new("9123456789".to_string()); assert_eq!("99*****299", format!("{}", secret)); } #[test] fn test_invalid_phone_number_masking() { let secret: Secret<String, PhoneNumber> = Secret::new("99229922".to_string()); assert_eq!("*** alloc::string::String ***", format!("{}", secret)); let secret: Secret<String, PhoneNumber> = Secret::new("9922992299229922".to_string()); assert_eq!("*** alloc::string::String ***", format!("{}", secret)); } */ #[test] fn test_valid_email_masking() { let secret: Secret<String, EmailStrategy> = Secret::new("example@test.com".to_string()); assert_eq!("*******@test.com", format!("{secret:?}")); let secret: Secret<String, EmailStrategy> = Secret::new("username@gmail.com".to_string()); assert_eq!("********@gmail.com", format!("{secret:?}")); } #[test] fn test_invalid_email_masking() { let secret: Secret<String, EmailStrategy> = Secret::new("myemailgmail.com".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); let secret: Secret<String, EmailStrategy> = Secret::new("myemail$gmail.com".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_newtype_email() { let email_check = Email::from_str("example@abc.com"); assert!(email_check.is_ok()); } #[test] fn test_invalid_newtype_email() { let email_check = Email::from_str("example@abc@com"); assert!(email_check.is_err()); } #[test] fn test_redacted_email() { let email_result = Email::from_str(REDACTED); assert!(email_result.is_ok()); if let Ok(email) = email_result { let secret_value = email.0.expose(); assert_eq!(secret_value.as_str(), REDACTED); } } #[test] fn test_valid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string()); assert_eq!("123.**.**.**", format!("{secret:?}")); } #[test] fn test_invalid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.4.56".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); let secret: Secret<String, IpAddress> = Secret::new("123.4567.12.4".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); let secret: Secret<String, IpAddress> = Secret::new("123..4.56".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_client_secret_masking() { let secret: Secret<String, ClientSecret> = Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret_tLjTz9tAQxUVEFqfmOIP".to_string()); assert_eq!( "pay_uszFB2QGe9MmLY65ojhT_***************************", format!("{secret:?}") ); } #[test] fn test_invalid_client_secret_masking() { let secret: Secret<String, IpAddress> = Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_phone_number_default_masking() { let secret: Secret<String> = Secret::new("+40712345678".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_upi_vpa_masking() { let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name@upi".to_string()); assert_eq!("*******@upi", format!("{secret:?}")); } #[test] fn test_invalid_upi_vpa_masking() { let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name_upi".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/ext_traits.rs
crates/common_utils/src/ext_traits.rs
//! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, Strategy}; use quick_xml::de; #[cfg(all(feature = "logs", feature = "async_ext"))] use router_env::logger; use serde::{Deserialize, Serialize}; use crate::{ crypto, errors::{self, CustomResult}, fp_utils::when, }; /// Encode interface /// An interface for performing type conversions and serialization pub trait Encode<'e> where Self: 'e + std::fmt::Debug, { // If needed get type information/custom error implementation. /// /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; } impl<'e, A> Encode<'e> for A where Self: 'e + std::fmt::Debug, { fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("string")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_urlencoded::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } // Check without two functions can we combine this fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_json::to_string(self) .change_context(errors::ParsingError::EncodeError("json")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { quick_xml::se::to_string(self) .change_context(errors::ParsingError::EncodeError("xml")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize, { serde_json::to_vec(self) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } } /// Extending functionalities of `bytes::Bytes` pub trait BytesExt { /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl BytesExt for bytes::Bytes { fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { use bytes::Buf; serde_json::from_slice::<T>(self.chunk()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let variable_type = std::any::type_name::<T>(); let value = serde_json::from_slice::<serde_json::Value>(self) .unwrap_or_else(|_| serde_json::Value::String(String::new())); format!( "Unable to parse {variable_type} from bytes {:?}", Secret::<_, masking::JsonMaskStrategy>::new(value) ) }) } } /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl ByteSliceExt for [u8] { #[track_caller] fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_slice(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let value = serde_json::from_slice::<serde_json::Value>(self) .unwrap_or_else(|_| serde_json::Value::String(String::new())); format!( "Unable to parse {type_name} from &[u8] {:?}", Secret::<_, masking::JsonMaskStrategy>::new(value) ) }) } } /// Extending functionalities of `serde_json::Value` for performing parsing pub trait ValueExt { /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned; } impl ValueExt for serde_json::Value { fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned, { serde_json::from_value::<T>(self.clone()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { format!( "Unable to parse {type_name} from serde_json::Value: {:?}", // Required to prevent logging sensitive data in case of deserialization failure Secret::<_, masking::JsonMaskStrategy>::new(self) ) }) } } impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy> where MaskingStrategy: Strategy<serde_json::Value>, { fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned, { self.expose().parse_value(type_name) } } impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> { fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned, { self.into_inner().parse_value(type_name) } } /// Extending functionalities of `String` for performing parsing pub trait StringExt<T> { /// Convert `String` into type `<T>` (which being an `enum`) fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl<T> StringExt<T> for String { fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static, { T::from_str(&self) .change_context(errors::ParsingError::EnumParseFailure(enum_name)) .attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}")) } fn parse_struct<'de>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_str::<T>(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { format!( "Unable to parse {type_name} from string {:?}", Secret::<_, masking::JsonMaskStrategy>::new(serde_json::Value::String( self.clone() )) ) }) } } /// Extending functionalities of Wrapper types for idiomatic #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] pub trait AsyncExt<A> { /// Output type of the map function type WrappedSelf<T>; /// Extending map by allowing functions which are async async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send; /// Extending the `and_then` by allowing functions which are async async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send; /// Extending `unwrap_or_else` to allow async fallback async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = A> + Send; /// Extending `or_else` to allow async fallback that returns Self::WrappedSelf<A> async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send; } #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> { type WrappedSelf<T> = Result<T, E>; async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send, { match self { Ok(a) => func(a).await, Err(err) => Err(err), } } async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, { match self { Ok(a) => Ok(func(a).await), Err(err) => Err(err), } } async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = A> + Send, { match self { Ok(a) => a, Err(_err) => { #[cfg(feature = "logs")] logger::error!("Error: {:?}", _err); func().await } } } async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send, { match self { Ok(a) => Ok(a), Err(_err) => { #[cfg(feature = "logs")] logger::error!("Error: {:?}", _err); func().await } } } } #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] impl<A: Send> AsyncExt<A> for Option<A> { type WrappedSelf<T> = Option<T>; async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send, { match self { Some(a) => func(a).await, None => None, } } async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, { match self { Some(a) => Some(func(a).await), None => None, } } async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = A> + Send, { match self { Some(a) => a, None => func().await, } } async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send, { match self { Some(a) => Some(a), None => func().await, } } } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt { /// Returns whether the value of `self` is the default value for `Self`. fn is_default(&self) -> bool where Self: Default + PartialEq<Self>, { *self == Self::default() } /// Returns whether the value of `self` is empty after trimming whitespace on both left and /// right ends. fn is_empty_after_trim(&self) -> bool; /// Returns whether the value of `self` is the default value for `Self` or empty after trimming /// whitespace on both left and right ends. fn is_default_or_empty(&self) -> bool where Self: Default + PartialEq<Self>, { self.is_default() || self.is_empty_after_trim() } } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false } } impl ConfigExt for String { fn is_empty_after_trim(&self) -> bool { self.trim().is_empty() } } impl<T, U> ConfigExt for Secret<T, U> where T: ConfigExt + Default + PartialEq<T>, U: Strategy<T>, { fn is_default(&self) -> bool where T: Default + PartialEq<T>, { *self.peek() == T::default() } fn is_empty_after_trim(&self) -> bool { self.peek().is_empty_after_trim() } fn is_default_or_empty(&self) -> bool where T: Default + PartialEq<T>, { self.peek().is_default() || self.peek().is_empty_after_trim() } } /// Extension trait for deserializing XML strings using `quick-xml` crate pub trait XmlExt { /// Deserialize an XML string into the specified type `<T>`. fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned; } impl XmlExt for &str { fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned, { de::from_str(self) } } /// Extension trait for Option to validate missing fields pub trait OptionExt<T> { /// check if the current option is Some fn check_value_present( &self, field_name: &'static str, ) -> CustomResult<(), errors::ValidationError>; /// Throw missing required field error when the value is None fn get_required_value( self, field_name: &'static str, ) -> CustomResult<T, errors::ValidationError>; /// Try parsing the option as Enum fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; /// Try parsing the option as Type fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned; /// update option value fn update_value(&mut self, value: Option<T>); } impl<T> OptionExt<T> for Option<T> where T: std::fmt::Debug, { #[track_caller] fn check_value_present( &self, field_name: &'static str, ) -> CustomResult<(), errors::ValidationError> { when(self.is_none(), || { Err(errors::ValidationError::MissingRequiredField { field_name: field_name.to_string(), }) .attach_printable(format!("Missing required field {field_name} in {self:?}")) }) } // This will allow the error message that was generated in this function to point to the call site #[track_caller] fn get_required_value( self, field_name: &'static str, ) -> CustomResult<T, errors::ValidationError> { match self { Some(v) => Ok(v), None => Err(errors::ValidationError::MissingRequiredField { field_name: field_name.to_string(), }) .attach_printable(format!("Missing required field {field_name} in {self:?}")), } } #[track_caller] fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static, { let value = self .get_required_value(enum_name) .change_context(errors::ParsingError::UnknownError)?; E::from_str(value.as_ref()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} ")) } #[track_caller] fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned, { let value = self .get_required_value(type_name) .change_context(errors::ParsingError::UnknownError)?; value.parse_value(type_name) } fn update_value(&mut self, value: Self) { if let Some(a) = value { *self = Some(a) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/ucs_types.rs
crates/common_utils/src/ucs_types.rs
use crate::id_type; /// Represents a reference ID for the Unified Connector Service (UCS). /// /// This enum can hold either a payment reference ID or a refund reference ID, /// allowing for a unified way to handle different types of transaction references /// when interacting with the UCS. #[derive(Debug)] pub enum UcsReferenceId { /// A payment reference ID. /// /// This variant wraps a [`PaymentReferenceId`](id_type::PaymentReferenceId) /// and is used to identify a payment transaction within the UCS. Payment(id_type::PaymentReferenceId), /// A refund reference ID. /// /// This variant wraps a [`RefundReferenceId`](id_type::RefundReferenceId) /// and is used to identify a refund transaction within the UCS. Refund(id_type::RefundReferenceId), } impl UcsReferenceId { /// Returns the string representation of the reference ID. /// /// This method matches the enum variant and calls the `get_string_repr` /// method of the underlying ID type (either `PaymentReferenceId` or `RefundReferenceId`) /// to get its string representation. /// /// # Returns /// /// A string slice (`&str`) representing the reference ID. pub fn get_string_repr(&self) -> &str { match self { Self::Payment(id) => id.get_string_repr(), Self::Refund(id) => id.get_string_repr(), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/validation.rs
crates/common_utils/src/validation.rs
//! Custom validations for some shared types. #![deny(clippy::invalid_regex)] use std::{collections::HashSet, sync::LazyLock}; use error_stack::report; use globset::Glob; use regex::Regex; #[cfg(feature = "logs")] use router_env::logger; use crate::errors::{CustomResult, ValidationError}; /// Validates a given phone number using the [phonenumber] crate /// /// It returns a [ValidationError::InvalidValue] in case it could not parse the phone number pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> { let _ = phonenumber::parse(None, phone_number).map_err(|e| ValidationError::InvalidValue { message: format!("Could not parse phone number: {phone_number}, because: {e:?}"), })?; Ok(()) } /// Performs a simple validation against a provided email address. pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> { #[deny(clippy::invalid_regex)] static EMAIL_REGEX: LazyLock<Option<Regex>> = LazyLock::new(|| { #[allow(unknown_lints)] #[allow(clippy::manual_ok_err)] match Regex::new( r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$", ) { Ok(regex) => Some(regex), Err(_error) => { #[cfg(feature = "logs")] logger::error!(?_error); None } } }); let email_regex = match EMAIL_REGEX.as_ref() { Some(regex) => Ok(regex), None => Err(report!(ValidationError::InvalidValue { message: "Invalid regex expression".into() })), }?; const EMAIL_MAX_LENGTH: usize = 319; if email.is_empty() || email.chars().count() > EMAIL_MAX_LENGTH { return Err(report!(ValidationError::InvalidValue { message: "Email address is either empty or exceeds maximum allowed length".into() })); } if !email_regex.is_match(email) { return Err(report!(ValidationError::InvalidValue { message: "Invalid email address format".into() })); } Ok(()) } /// Checks whether a given domain matches against a list of valid domain glob patterns pub fn validate_domain_against_allowed_domains( domain: &str, allowed_domains: HashSet<String>, ) -> bool { allowed_domains.iter().any(|allowed_domain| { Glob::new(allowed_domain) .map(|glob| glob.compile_matcher().is_match(domain)) .map_err(|err| { let err_msg = format!( "Invalid glob pattern for configured allowed_domain [{allowed_domain:?}]! - {err:?}", ); #[cfg(feature = "logs")] logger::error!(err_msg); err_msg }) .unwrap_or(false) }) } /// checks whether the input string contains potential XSS or SQL injection attack vectors pub fn contains_potential_xss_or_sqli(input: &str) -> bool { let decoded = urlencoding::decode(input).unwrap_or_else(|_| input.into()); // Check for suspicious percent-encoded patterns static PERCENT_ENCODED: LazyLock<Option<Regex>> = LazyLock::new(|| { Regex::new(r"%[0-9A-Fa-f]{2}") .map_err(|_err| { #[cfg(feature = "logs")] logger::error!(?_err); }) .ok() }); if decoded.contains('%') { match PERCENT_ENCODED.as_ref() { Some(regex) => { if regex.is_match(&decoded) { return true; } } None => return true, } } if ammonia::is_html(&decoded) { return true; } static XSS: LazyLock<Option<Regex>> = LazyLock::new(|| { Regex::new( r"(?is)\bon[a-z]+\s*=|\bjavascript\s*:|\bdata\s*:\s*text/html|\b(alert|prompt|confirm|eval)\s*\(", ) .map_err(|_err| { #[cfg(feature = "logs")] logger::error!(?_err); }) .ok() }); static SQLI: LazyLock<Option<Regex>> = LazyLock::new(|| { Regex::new( r"(?is)(?:')\s*or\s*'?\d+'?=?\d*|union\s+select|insert\s+into|drop\s+table|information_schema|sleep\s*\(|--|;", ) .map_err(|_err| { #[cfg(feature = "logs")] logger::error!(?_err); }) .ok() }); match XSS.as_ref() { Some(regex) => { if regex.is_match(&decoded) { return true; } } None => return true, } match SQLI.as_ref() { Some(regex) => { if regex.is_match(&decoded) { return true; } } None => return true, } false } #[cfg(test)] mod tests { use fake::{faker::internet::en::SafeEmail, Fake}; use proptest::{ prop_assert, strategy::{Just, NewTree, Strategy}, test_runner::TestRunner, }; use test_case::test_case; use super::*; #[derive(Debug)] struct ValidEmail; impl Strategy for ValidEmail { type Tree = Just<String>; type Value = String; fn new_tree(&self, _runner: &mut TestRunner) -> NewTree<Self> { Ok(Just(SafeEmail().fake())) } } #[test] fn test_validate_email() { let result = validate_email("abc@example.com"); assert!(result.is_ok()); let result = validate_email("abc+123@example.com"); assert!(result.is_ok()); let result = validate_email(""); assert!(result.is_err()); } #[test_case("+40745323456" ; "Romanian valid phone number")] #[test_case("+34912345678" ; "Spanish valid phone number")] #[test_case("+41 79 123 45 67" ; "Swiss valid phone number")] #[test_case("+66 81 234 5678" ; "Thailand valid phone number")] fn test_validate_phone_number(phone_number: &str) { assert!(validate_phone_number(phone_number).is_ok()); } #[test_case("9123456789" ; "Romanian invalid phone number")] fn test_invalid_phone_number(phone_number: &str) { let res = validate_phone_number(phone_number); assert!(res.is_err()); } proptest::proptest! { /// Example of unit test #[test] fn proptest_valid_fake_email(email in ValidEmail) { prop_assert!(validate_email(&email).is_ok()); } /// Example of unit test #[test] fn proptest_invalid_data_email(email in "\\PC*") { prop_assert!(validate_email(&email).is_err()); } #[test] fn proptest_invalid_email(email in "[.+]@(.+)") { prop_assert!(validate_email(&email).is_err()); } } #[test] fn detects_basic_script_tags() { assert!(contains_potential_xss_or_sqli( "<script>alert('xss')</script>" )); } #[test] fn detects_event_handlers() { assert!(contains_potential_xss_or_sqli( "onload=alert('xss') onclick=alert('xss') onmouseover=alert('xss')", )); } #[test] fn detects_data_url_payload() { assert!(contains_potential_xss_or_sqli( "data:text/html,<script>alert('xss')</script>", )); } #[test] fn detects_iframe_javascript_src() { assert!(contains_potential_xss_or_sqli( "<iframe src=javascript:alert('xss')></iframe>", )); } #[test] fn detects_svg_with_script() { assert!(contains_potential_xss_or_sqli( "<svg><script>alert('xss')</script></svg>", )); } #[test] fn detects_object_with_js() { assert!(contains_potential_xss_or_sqli( "<object data=javascript:alert('xss')></object>", )); } #[test] fn detects_mixed_case_tags() { assert!(contains_potential_xss_or_sqli( "<ScRiPt>alert('xss')</ScRiPt>" )); } #[test] fn detects_embedded_script_in_text() { assert!(contains_potential_xss_or_sqli( "Test<script>alert('xss')</script>Company", )); } #[test] fn detects_math_with_script() { assert!(contains_potential_xss_or_sqli( "<math><script>alert('xss')</script></math>", )); } #[test] fn detects_basic_sql_tautology() { assert!(contains_potential_xss_or_sqli("' OR '1'='1")); } #[test] fn detects_time_based_sqli() { assert!(contains_potential_xss_or_sqli("' OR SLEEP(5) --")); } #[test] fn detects_percent_encoded_sqli() { // %27 OR %271%27=%271 is a typical encoded variant assert!(contains_potential_xss_or_sqli("%27%20OR%20%271%27%3D%271")); } #[test] fn detects_benign_html_as_suspicious() { assert!(contains_potential_xss_or_sqli("<b>Hello</b>")); } #[test] fn allows_legitimate_plain_text() { assert!(!contains_potential_xss_or_sqli("My Test Company Ltd.")); } #[test] fn allows_normal_url() { assert!(!contains_potential_xss_or_sqli("https://example.com")); } #[test] fn allows_percent_char_without_encoding() { assert!(!contains_potential_xss_or_sqli("Get 50% off today")); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/encryption.rs
crates/common_utils/src/encryption.rs
use diesel::{ backend::Backend, deserialize::{self, FromSql, Queryable}, expression::AsExpression, serialize::ToSql, sql_types, }; use masking::Secret; use crate::{crypto::Encryptable, pii::EncryptionStrategy}; impl<DB> FromSql<sql_types::Binary, DB> for Encryption where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { <Secret<Vec<u8>, EncryptionStrategy>>::from_sql(bytes).map(Self::new) } } impl<DB> ToSql<sql_types::Binary, DB> for Encryption where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: ToSql<sql_types::Binary, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.get_inner().to_sql(out) } } impl<DB> Queryable<sql_types::Binary, DB> for Encryption where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>, { type Row = Secret<Vec<u8>, EncryptionStrategy>; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(Self { inner: row }) } } #[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[diesel(sql_type = sql_types::Binary)] #[repr(transparent)] pub struct Encryption { inner: Secret<Vec<u8>, EncryptionStrategy>, } impl<T: Clone> From<Encryptable<T>> for Encryption { fn from(value: Encryptable<T>) -> Self { Self::new(value.into_encrypted()) } } impl Encryption { pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { Self { inner: item } } #[inline] pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.inner } #[inline] pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> { &self.inner } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type.rs
crates/common_utils/src/id_type.rs
//! Common ID types //! The id type can be used to create specific id types with custom behaviour mod api_key; mod authentication; mod client_secret; mod customer; #[cfg(feature = "v2")] mod global_id; mod invoice; mod merchant; mod merchant_connector_account; mod organization; mod payment; mod payout; mod profile; mod profile_acquirer; mod refunds; mod relay; mod routing; mod subscription; mod tenant; mod webhook_endpoint; use std::{borrow::Cow, fmt::Debug}; use diesel::{ backend::Backend, deserialize::FromSql, expression::AsExpression, serialize::{Output, ToSql}, sql_types, }; pub use payout::PayoutId; use serde::{Deserialize, Serialize}; use thiserror::Error; #[cfg(feature = "v2")] pub use self::global_id::{ customer::GlobalCustomerId, payment::{GlobalAttemptGroupId, GlobalAttemptId, GlobalPaymentId}, payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId}, refunds::GlobalRefundId, token::GlobalTokenId, CellId, }; pub use self::{ api_key::ApiKeyId, authentication::AuthenticationId, client_secret::ClientSecretId, customer::CustomerId, invoice::InvoiceId, merchant::MerchantId, merchant_connector_account::MerchantConnectorAccountId, organization::OrganizationId, payment::{PaymentId, PaymentReferenceId}, profile::ProfileId, profile_acquirer::ProfileAcquirerId, refunds::RefundReferenceId, relay::RelayId, routing::RoutingId, subscription::SubscriptionId, tenant::TenantId, webhook_endpoint::WebhookEndpointId, }; use crate::{fp_utils::when, generate_id_with_default_len}; #[inline] fn is_valid_id_character(input_char: char) -> bool { input_char.is_ascii_alphanumeric() || matches!(input_char, '_' | '-') } /// This functions checks for the input string to contain valid characters /// Returns Some(char) if there are any invalid characters, else None fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char> { input_string .trim() .chars() .find(|&char| !is_valid_id_character(char)) } #[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)] /// A type for alphanumeric ids pub(crate) struct AlphaNumericId(String); #[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)] #[error("value `{0}` contains invalid character `{1}`")] /// The error type for alphanumeric id pub(crate) struct AlphaNumericIdError(String, char); impl<'de> Deserialize<'de> for AlphaNumericId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from(deserialized_string.into()).map_err(serde::de::Error::custom) } } impl AlphaNumericId { /// Creates a new alphanumeric id from string by applying validation checks pub fn from(input_string: Cow<'static, str>) -> Result<Self, AlphaNumericIdError> { let invalid_character = get_invalid_input_character(input_string.clone()); if let Some(invalid_character) = invalid_character { Err(AlphaNumericIdError( input_string.to_string(), invalid_character, ))? } Ok(Self(input_string.to_string())) } /// Create a new alphanumeric id without any validations pub(crate) fn new_unchecked(input_string: String) -> Self { Self(input_string) } /// Generate a new alphanumeric id of default length pub(crate) fn new(prefix: &str) -> Self { Self(generate_id_with_default_len(prefix)) } } /// A common type of id that can be used for reference ids with length constraint #[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(AlphaNumericId); /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum LengthIdError { #[error("the maximum allowed length for this field is {0}")] /// Maximum length of string violated MaxLengthViolated(u8), #[error("the minimum required length for this field is {0}")] /// Minimum length of string violated MinLengthViolated(u8), #[error("{0}")] /// Input contains invalid characters AlphanumericIdError(AlphaNumericIdError), } impl From<AlphaNumericIdError> for LengthIdError { fn from(alphanumeric_id_error: AlphaNumericIdError) -> Self { Self::AlphanumericIdError(alphanumeric_id_error) } } impl<const MAX_LENGTH: u8, const MIN_LENGTH: u8> LengthId<MAX_LENGTH, MIN_LENGTH> { /// Generates new [MerchantReferenceId] from the given input string pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthIdError> { let trimmed_input_string = input_string.trim().to_string(); let length_of_input_string = u8::try_from(trimmed_input_string.len()) .map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?; when(length_of_input_string > MAX_LENGTH, || { Err(LengthIdError::MaxLengthViolated(MAX_LENGTH)) })?; when(length_of_input_string < MIN_LENGTH, || { Err(LengthIdError::MinLengthViolated(MIN_LENGTH)) })?; let alphanumeric_id = match AlphaNumericId::from(trimmed_input_string.into()) { Ok(valid_alphanumeric_id) => valid_alphanumeric_id, Err(error) => Err(LengthIdError::AlphanumericIdError(error))?, }; Ok(Self(alphanumeric_id)) } /// Generate a new MerchantRefId of default length with the given prefix pub fn new(prefix: &str) -> Self { Self(AlphaNumericId::new(prefix)) } /// Use this function only if you are sure that the length is within the range pub(crate) fn new_unchecked(alphanumeric_id: AlphaNumericId) -> Self { Self(alphanumeric_id) } #[cfg(feature = "v2")] /// Create a new LengthId from aplhanumeric id pub(crate) fn from_alphanumeric_id( alphanumeric_id: AlphaNumericId, ) -> Result<Self, LengthIdError> { let length_of_input_string = alphanumeric_id.0.len(); let length_of_input_string = u8::try_from(length_of_input_string) .map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?; when(length_of_input_string > MAX_LENGTH, || { Err(LengthIdError::MaxLengthViolated(MAX_LENGTH)) })?; when(length_of_input_string < MIN_LENGTH, || { Err(LengthIdError::MinLengthViolated(MIN_LENGTH)) })?; Ok(Self(alphanumeric_id)) } } impl<'de, const MAX_LENGTH: u8, const MIN_LENGTH: u8> Deserialize<'de> for LengthId<MAX_LENGTH, MIN_LENGTH> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from(deserialized_string.into()).map_err(serde::de::Error::custom) } } impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> ToSql<sql_types::Text, DB> for LengthId<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0 .0.to_sql(out) } } impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> FromSql<sql_types::Text, DB> for LengthId<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let string_val = String::from_sql(value)?; Ok(Self(AlphaNumericId::new_unchecked(string_val))) } } /// An interface to generate object identifiers. pub trait GenerateId { /// Generates a random object identifier. fn generate() -> Self; } #[cfg(test)] mod alphanumeric_id_tests { use super::*; const VALID_UNDERSCORE_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#; const EXPECTED_VALID_UNDERSCORE_ID: &str = "cus_abcdefghijklmnopqrstuv"; const VALID_HYPHEN_ID_JSON: &str = r#""cus-abcdefghijklmnopqrstuv""#; const VALID_HYPHEN_ID_STRING: &str = "cus-abcdefghijklmnopqrstuv"; const INVALID_ID_WITH_SPACES: &str = r#""cus abcdefghijklmnopqrstuv""#; const INVALID_ID_WITH_EMOJIS: &str = r#""cus_abc🦀""#; #[test] fn test_id_deserialize_underscore() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(VALID_UNDERSCORE_ID_JSON); let alphanumeric_id = AlphaNumericId::from(EXPECTED_VALID_UNDERSCORE_ID.into()).unwrap(); assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id); } #[test] fn test_id_deserialize_hyphen() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(VALID_HYPHEN_ID_JSON); let alphanumeric_id = AlphaNumericId::from(VALID_HYPHEN_ID_STRING.into()).unwrap(); assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id); } #[test] fn test_id_deserialize_with_spaces() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_SPACES); assert!(parsed_alphanumeric_id.is_err()); } #[test] fn test_id_deserialize_with_emojis() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_EMOJIS); assert!(parsed_alphanumeric_id.is_err()); } } #[cfg(test)] mod merchant_reference_id_tests { use super::*; const VALID_REF_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#; const MAX_LENGTH: u8 = 36; const MIN_LENGTH: u8 = 6; const INVALID_REF_ID_JSON: &str = r#""cus abcdefghijklmnopqrstuv""#; const INVALID_REF_ID_LENGTH: &str = r#""cus_abcdefghijklmnopqrstuvwxyzabcdefghij""#; #[test] fn test_valid_reference_id() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(VALID_REF_ID_JSON); dbg!(&parsed_merchant_reference_id); assert!(parsed_merchant_reference_id.is_ok()); } #[test] fn test_invalid_ref_id() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON); assert!(parsed_merchant_reference_id.is_err()); } #[test] fn test_invalid_ref_id_error_message() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON); let expected_error_message = r#"value `cus abcdefghijklmnopqrstuv` contains invalid character ` `"#.to_string(); let error_message = parsed_merchant_reference_id .err() .map(|error| error.to_string()); assert_eq!(error_message, Some(expected_error_message)); } #[test] fn test_invalid_ref_id_length() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_LENGTH); dbg!(&parsed_merchant_reference_id); let expected_error_message = format!("the maximum allowed length for this field is {MAX_LENGTH}"); assert!(parsed_merchant_reference_id .is_err_and(|error_string| error_string.to_string().eq(&expected_error_message))); } #[test] fn test_invalid_ref_id_length_error_type() { let parsed_merchant_reference_id = LengthId::<MAX_LENGTH, MIN_LENGTH>::from(INVALID_REF_ID_LENGTH.into()); dbg!(&parsed_merchant_reference_id); assert!( parsed_merchant_reference_id.is_err_and(|error_type| matches!( error_type, LengthIdError::MaxLengthViolated(MAX_LENGTH) )) ); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/new_type.rs
crates/common_utils/src/new_type.rs
//! Contains new types with restrictions use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH, pii::{Email, UpiVpaMaskingStrategy}, transformers::ForeignFrom, }; #[nutype::nutype( derive(Clone, Serialize, Deserialize, Debug), validate(len_char_min = 1, len_char_max = MAX_ALLOWED_MERCHANT_NAME_LENGTH) )] pub struct MerchantName(String); impl masking::SerializableSecret for MerchantName {} /// Function for masking alphanumeric characters in a string. /// /// # Arguments /// `val` /// - holds reference to the string to be masked. /// `unmasked_char_count` /// - minimum character count to remain unmasked for identification /// - this number is for keeping the characters unmasked from /// both beginning (if feasible) and ending of the string. /// `min_masked_char_count` /// - this ensures the minimum number of characters to be masked /// /// # Behaviour /// - Returns the original string if its length is less than or equal to `unmasked_char_count`. /// - If the string length allows, keeps `unmasked_char_count` characters unmasked at both start and end. /// - Otherwise, keeps `unmasked_char_count` characters unmasked only at the end. /// - Only alphanumeric characters are masked; other characters remain unchanged. /// /// # Examples /// Sort Code /// (12-34-56, 2, 2) -> 12-**-56 /// Routing number /// (026009593, 3, 3) -> 026***593 /// CNPJ /// (12345678901, 4, 4) -> *******8901 /// CNPJ /// (12345678901, 4, 3) -> 1234***8901 /// Pix key /// (123e-a452-1243-1244-000, 4, 4) -> 123e-****-****-****-000 /// IBAN /// (AL35202111090000000001234567, 5, 5) -> AL352******************34567 fn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String { let len = val.len(); if len <= unmasked_char_count { return val.to_string(); } let mask_start_index = // For showing only last `unmasked_char_count` characters if len < (unmasked_char_count * 2 + min_masked_char_count) { 0 // For showing first and last `unmasked_char_count` characters } else { unmasked_char_count }; let mask_end_index = len - unmasked_char_count - 1; let range = mask_start_index..=mask_end_index; val.chars() .enumerate() .fold(String::new(), |mut acc, (index, ch)| { if ch.is_alphanumeric() && range.contains(&index) { acc.push('*'); } else { acc.push(ch); } acc }) } /// Masked sort code #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedSortCode(Secret<String>); impl From<String> for MaskedSortCode { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 2, 2); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedSortCode { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked Routing number #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedRoutingNumber(Secret<String>); impl From<String> for MaskedRoutingNumber { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 3); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedRoutingNumber { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked bank account #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedBankAccount(Secret<String>); impl From<String> for MaskedBankAccount { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 4, 4); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedBankAccount { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked IBAN #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedIban(Secret<String>); impl From<String> for MaskedIban { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 5, 5); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedIban { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked IBAN #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedBic(Secret<String>); impl From<String> for MaskedBic { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 2); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedBic { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked UPI ID #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedUpiVpaId(Secret<String>); impl From<String> for MaskedUpiVpaId { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if let Some((user_identifier, bank_or_psp)) = src.split_once('@') { let masked_user_identifier = user_identifier .to_string() .chars() .take(unmasked_char_count) .collect::<String>() + &"*".repeat(user_identifier.len() - unmasked_char_count); format!("{masked_user_identifier}@{bank_or_psp}") } else { let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8); masked_value }; Self(Secret::from(masked_value)) } } impl From<Secret<String, UpiVpaMaskingStrategy>> for MaskedUpiVpaId { fn from(secret: Secret<String, UpiVpaMaskingStrategy>) -> Self { Self::from(secret.expose()) } } /// Masked Email #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedEmail(Secret<String>); impl From<String> for MaskedEmail { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if let Some((user_identifier, domain)) = src.split_once('@') { let masked_user_identifier = user_identifier .to_string() .chars() .take(unmasked_char_count) .collect::<String>() + &"*".repeat(user_identifier.len() - unmasked_char_count); format!("{masked_user_identifier}@{domain}") } else { let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8); masked_value }; Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedEmail { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } impl ForeignFrom<Email> for MaskedEmail { fn foreign_from(email: Email) -> Self { let email_value: String = email.expose().peek().to_owned(); Self::from(email_value) } } /// Masked Phone Number #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedPhoneNumber(Secret<String>); impl From<String> for MaskedPhoneNumber { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if unmasked_char_count <= src.len() { let len = src.len(); // mask every character except the last 2 "*".repeat(len - unmasked_char_count).to_string() + src .get(len.saturating_sub(unmasked_char_count)..) .unwrap_or("") } else { src }; Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedPhoneNumber { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked Psp token #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedPspToken(Secret<String>); impl From<String> for MaskedPspToken { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 3); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedPspToken { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } #[cfg(test)] mod apply_mask_fn_test { use masking::PeekInterface; use crate::new_type::{ apply_mask, MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; #[test] fn test_masked_types() { let sort_code = MaskedSortCode::from("110011".to_string()); let routing_number = MaskedRoutingNumber::from("056008849".to_string()); let bank_account = MaskedBankAccount::from("12345678901234".to_string()); let iban = MaskedIban::from("NL02ABNA0123456789".to_string()); let upi_vpa = MaskedUpiVpaId::from("someusername@okhdfcbank".to_string()); // Standard masked data tests assert_eq!(sort_code.0.peek().to_owned(), "11**11".to_string()); assert_eq!(routing_number.0.peek().to_owned(), "056***849".to_string()); assert_eq!( bank_account.0.peek().to_owned(), "1234******1234".to_string() ); assert_eq!(iban.0.peek().to_owned(), "NL02A********56789".to_string()); assert_eq!( upi_vpa.0.peek().to_owned(), "so**********@okhdfcbank".to_string() ); } #[test] fn test_apply_mask_fn() { let value = "12345678901".to_string(); // Generic masked tests assert_eq!(apply_mask(&value, 2, 2), "12*******01".to_string()); assert_eq!(apply_mask(&value, 3, 2), "123*****901".to_string()); assert_eq!(apply_mask(&value, 3, 3), "123*****901".to_string()); assert_eq!(apply_mask(&value, 4, 3), "1234***8901".to_string()); assert_eq!(apply_mask(&value, 4, 4), "*******8901".to_string()); assert_eq!(apply_mask(&value, 5, 4), "******78901".to_string()); assert_eq!(apply_mask(&value, 5, 5), "******78901".to_string()); assert_eq!(apply_mask(&value, 6, 5), "*****678901".to_string()); assert_eq!(apply_mask(&value, 6, 6), "*****678901".to_string()); assert_eq!(apply_mask(&value, 7, 6), "****5678901".to_string()); assert_eq!(apply_mask(&value, 7, 7), "****5678901".to_string()); assert_eq!(apply_mask(&value, 8, 7), "***45678901".to_string()); assert_eq!(apply_mask(&value, 8, 8), "***45678901".to_string()); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/keymanager.rs
crates/common_utils/src/keymanager.rs
//! Consists of all the common functions to use the Keymanager. use core::fmt::Debug; use std::str::FromStr; use base64::Engine; use error_stack::ResultExt; use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; use masking::{PeekInterface, StrongSecret}; use once_cell::sync::OnceCell; use router_env::{instrument, logger, tracing}; use crate::{ consts::{BASE64_ENGINE, TENANT_HEADER}, errors, types::keymanager::{ BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest, EncryptionCreateRequest, EncryptionTransferRequest, GetKeymanagerTenant, KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; const CONTENT_TYPE: &str = "Content-Type"; static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); static DEFAULT_ENCRYPTION_VERSION: &str = "v1"; #[cfg(feature = "km_forward_x_request_id")] const X_REQUEST_ID: &str = "X-Request-Id"; /// Get keymanager client constructed from the url and state #[instrument(skip_all)] #[allow(unused_mut)] fn get_api_encryption_client( state: &KeyManagerState, ) -> errors::CustomResult<reqwest::Client, errors::KeyManagerClientError> { let get_client = || { let mut client = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .pool_idle_timeout(std::time::Duration::from_secs( state.client_idle_timeout.unwrap_or_default(), )); #[cfg(feature = "keymanager_mtls")] { let cert = state.cert.clone(); let ca = state.ca.clone(); let identity = reqwest::Identity::from_pem(cert.peek().as_ref()) .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; let ca_cert = reqwest::Certificate::from_pem(ca.peek().as_ref()) .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; client = client .use_rustls_tls() .identity(identity) .add_root_certificate(ca_cert) .https_only(true); } client .build() .change_context(errors::KeyManagerClientError::ClientConstructionFailed) }; Ok(ENCRYPTION_API_CLIENT.get_or_try_init(get_client)?.clone()) } /// Generic function to send the request to keymanager #[instrument(skip_all)] pub async fn send_encryption_request<T>( state: &KeyManagerState, headers: HeaderMap, url: String, method: Method, request_body: T, ) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError> where T: ConvertRaw, { let client = get_api_encryption_client(state)?; let url = reqwest::Url::parse(&url) .change_context(errors::KeyManagerClientError::UrlEncodingFailed)?; client .request(method, url) .json(&ConvertRaw::convert_raw(request_body)?) .headers(headers) .send() .await .change_context(errors::KeyManagerClientError::RequestNotSent( "Unable to send request to encryption service".to_string(), )) } /// Generic function to call the Keymanager and parse the response back #[instrument(skip_all)] pub async fn call_encryption_service<T, R>( state: &KeyManagerState, method: Method, endpoint: &str, request_body: T, ) -> errors::CustomResult<R, errors::KeyManagerClientError> where T: GetKeymanagerTenant + ConvertRaw + Send + Sync + 'static + Debug, R: serde::de::DeserializeOwned, { let url = format!("{}/{endpoint}", &state.url); logger::info!(key_manager_request=?request_body); let mut header = vec![]; header.push(( HeaderName::from_str(CONTENT_TYPE) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, HeaderValue::from_str("application/json") .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )); #[cfg(feature = "km_forward_x_request_id")] if let Some(ref request_id) = state.request_id { header.push(( HeaderName::from_str(X_REQUEST_ID) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, HeaderValue::from_str(request_id.as_str()) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )) } //Add Tenant ID header.push(( HeaderName::from_str(TENANT_HEADER) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, HeaderValue::from_str(request_body.get_tenant_id(state).get_string_repr()) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )); let response = send_encryption_request( state, HeaderMap::from_iter(header.into_iter()), url, method, request_body, ) .await .map_err(|err| err.change_context(errors::KeyManagerClientError::RequestSendFailed))?; logger::info!(key_manager_response=?response); match response.status() { StatusCode::OK => response .json::<R>() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed), StatusCode::INTERNAL_SERVER_ERROR => { Err(errors::KeyManagerClientError::InternalServerError( response .bytes() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, ) .into()) } StatusCode::BAD_REQUEST => Err(errors::KeyManagerClientError::BadRequest( response .bytes() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, ) .into()), _ => Err(errors::KeyManagerClientError::Unexpected( response .bytes() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, ) .into()), } } /// Trait to convert the raw data to the required format for encryption service request pub trait ConvertRaw { /// Return type of the convert_raw function type Output: serde::Serialize; /// Function to convert the raw data to the required format for encryption service request fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>; } impl<T: serde::Serialize> ConvertRaw for T { type Output = T; fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { Ok(self) } } impl ConvertRaw for TransientDecryptDataRequest { type Output = DecryptDataRequest; fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { let data = match String::from_utf8(self.data.peek().clone()) { Ok(data) => data, Err(_) => { let data = BASE64_ENGINE.encode(self.data.peek().clone()); format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") } }; Ok(DecryptDataRequest { identifier: self.identifier, data: StrongSecret::new(data), }) } } impl ConvertRaw for TransientBatchDecryptDataRequest { type Output = BatchDecryptDataRequest; fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { let data = self .data .iter() .map(|(k, v)| { let value = match String::from_utf8(v.peek().clone()) { Ok(data) => data, Err(_) => { let data = BASE64_ENGINE.encode(v.peek().clone()); format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") } }; (k.to_owned(), StrongSecret::new(value)) }) .collect(); Ok(BatchDecryptDataRequest { data, identifier: self.identifier, }) } } /// A function to create the key in keymanager #[instrument(skip_all)] pub async fn create_key_in_key_manager( state: &KeyManagerState, request_body: EncryptionCreateRequest, ) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { call_encryption_service(state, Method::POST, "key/create", request_body) .await .change_context(errors::KeyManagerError::KeyAddFailed) } /// A function to transfer the key in keymanager #[instrument(skip_all)] pub async fn transfer_key_to_key_manager( state: &KeyManagerState, request_body: EncryptionTransferRequest, ) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { call_encryption_service(state, Method::POST, "key/transfer", request_body) .await .change_context(errors::KeyManagerError::KeyTransferFailed) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types.rs
crates/common_utils/src/types.rs
//! Types that can be used in other crates pub mod keymanager; /// Enum for Authentication Level pub mod authentication; /// User related types pub mod user; /// types that are wrappers around primitive types pub mod primitive_wrappers; use std::{ borrow::Cow, fmt::Display, iter::Sum, num::NonZeroI64, ops::{Add, Mul, Sub}, primitive::i64, str::FromStr, }; use common_enums::enums; use diesel::{ backend::Backend, deserialize, deserialize::FromSql, serialize::{Output, ToSql}, sql_types, sql_types::Jsonb, AsExpression, FromSqlRow, Queryable, }; use error_stack::{report, ResultExt}; pub use primitive_wrappers::bool_wrappers::{ AlwaysRequestExtendedAuthorization, ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use rust_decimal::{ prelude::{FromPrimitive, ToPrimitive}, Decimal, }; use semver::Version; use serde::{de::Visitor, Deserialize, Deserializer, Serialize}; use thiserror::Error; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{ consts::{ self, MAX_DESCRIPTION_LENGTH, MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH, }, errors::{CustomResult, ParsingError, PercentageError, ValidationError}, fp_utils::when, id_type, impl_enum_str, }; /// Represents Percentage Value between 0 and 100 both inclusive #[derive(Clone, Default, Debug, PartialEq, Serialize)] pub struct Percentage<const PRECISION: u8> { // this value will range from 0 to 100, decimal length defined by precision macro /// Percentage value ranging between 0 and 100 percentage: f32, } fn get_invalid_percentage_error_message(precision: u8) -> String { format!( "value should be a float between 0 to 100 and precise to only upto {precision} decimal digits", ) } impl<const PRECISION: u8> Percentage<PRECISION> { /// construct percentage using a string representation of float value pub fn from_string(value: String) -> CustomResult<Self, PercentageError> { if Self::is_valid_string_value(&value)? { Ok(Self { percentage: value .parse::<f32>() .change_context(PercentageError::InvalidPercentageValue)?, }) } else { Err(report!(PercentageError::InvalidPercentageValue)) .attach_printable(get_invalid_percentage_error_message(PRECISION)) } } /// function to get percentage value pub fn get_percentage(&self) -> f32 { self.percentage } /// apply the percentage to amount and ceil the result #[allow(clippy::as_conversions)] pub fn apply_and_ceil_result( &self, amount: MinorUnit, ) -> CustomResult<MinorUnit, PercentageError> { let max_amount = i64::MAX / 10000; let amount = amount.0; if amount > max_amount { // value gets rounded off after i64::MAX/10000 Err(report!(PercentageError::UnableToApplyPercentage { percentage: self.percentage, amount: MinorUnit::new(amount), })) .attach_printable(format!( "Cannot calculate percentage for amount greater than {max_amount}", )) } else { let percentage_f64 = f64::from(self.percentage); let result = (amount as f64 * (percentage_f64 / 100.0)).ceil() as i64; Ok(MinorUnit::new(result)) } } fn is_valid_string_value(value: &str) -> CustomResult<bool, PercentageError> { let float_value = Self::is_valid_float_string(value)?; Ok(Self::is_valid_range(float_value) && Self::is_valid_precision_length(value)) } fn is_valid_float_string(value: &str) -> CustomResult<f32, PercentageError> { value .parse::<f32>() .change_context(PercentageError::InvalidPercentageValue) } fn is_valid_range(value: f32) -> bool { (0.0..=100.0).contains(&value) } fn is_valid_precision_length(value: &str) -> bool { if value.contains('.') { // if string has '.' then take the decimal part and verify precision length match value.split('.').next_back() { Some(decimal_part) => { decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION) } // will never be None None => false, } } else { // if there is no '.' then it is a whole number with no decimal part. So return true true } } } // custom serde deserialization function struct PercentageVisitor<const PRECISION: u8> {} impl<'de, const PRECISION: u8> Visitor<'de> for PercentageVisitor<PRECISION> { type Value = Percentage<PRECISION>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Percentage object") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de>, { let mut percentage_value = None; while let Some(key) = map.next_key::<String>()? { if key.eq("percentage") { if percentage_value.is_some() { return Err(serde::de::Error::duplicate_field("percentage")); } percentage_value = Some(map.next_value::<serde_json::Value>()?); } else { // Ignore unknown fields let _: serde::de::IgnoredAny = map.next_value()?; } } if let Some(value) = percentage_value { let string_value = value.to_string(); Ok(Percentage::from_string(string_value.clone()).map_err(|_| { serde::de::Error::invalid_value( serde::de::Unexpected::Other(&format!("percentage value {string_value}")), &&*get_invalid_percentage_error_message(PRECISION), ) })?) } else { Err(serde::de::Error::missing_field("percentage")) } } } impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> { fn deserialize<D>(data: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { data.deserialize_map(PercentageVisitor::<PRECISION> {}) } } /// represents surcharge type and value #[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum Surcharge { /// Fixed Surcharge value Fixed(MinorUnit), /// Surcharge percentage Rate(Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>), } /// This struct lets us represent a semantic version type #[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)] #[diesel(sql_type = Jsonb)] #[derive(Serialize, serde::Deserialize)] pub struct SemanticVersion(#[serde(with = "Version")] Version); impl SemanticVersion { /// returns major version number pub fn get_major(&self) -> u64 { self.0.major } /// returns minor version number pub fn get_minor(&self) -> u64 { self.0.minor } /// Constructs new SemanticVersion instance pub fn new(major: u64, minor: u64, patch: u64) -> Self { Self(Version::new(major, minor, patch)) } } impl Display for SemanticVersion { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl FromStr for SemanticVersion { type Err = error_stack::Report<ParsingError>; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self(Version::from_str(s).change_context( ParsingError::StructParseFailure("SemanticVersion"), )?)) } } crate::impl_to_sql_from_sql_json!(SemanticVersion); /// Amount convertor trait for connector pub trait AmountConvertor: Send { /// Output type for the connector type Output; /// helps in conversion of connector required amount type fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>>; /// helps in converting back connector required amount type to core minor unit fn convert_back( &self, amount: Self::Output, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>>; } /// Connector required amount type #[derive(Default, Debug, Clone, Copy, PartialEq)] pub struct StringMinorUnitForConnector; impl AmountConvertor for StringMinorUnitForConnector { type Output = StringMinorUnit; fn convert( &self, amount: MinorUnit, _currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_string() } fn convert_back( &self, amount: Self::Output, _currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64() } } /// Core required conversion type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct StringMajorUnitForCore; impl AmountConvertor for StringMajorUnitForCore { type Output = StringMajorUnit; fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_major_unit_as_string(currency) } fn convert_back( &self, amount: StringMajorUnit, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64(currency) } } /// Connector required amount type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct StringMajorUnitForConnector; impl AmountConvertor for StringMajorUnitForConnector { type Output = StringMajorUnit; fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_major_unit_as_string(currency) } fn convert_back( &self, amount: StringMajorUnit, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64(currency) } } /// Connector required amount type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct FloatMajorUnitForConnector; impl AmountConvertor for FloatMajorUnitForConnector { type Output = FloatMajorUnit; fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_major_unit_as_f64(currency) } fn convert_back( &self, amount: FloatMajorUnit, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64(currency) } } /// Connector required amount type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct MinorUnitForConnector; impl AmountConvertor for MinorUnitForConnector { type Output = MinorUnit; fn convert( &self, amount: MinorUnit, _currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { Ok(amount) } fn convert_back( &self, amount: MinorUnit, _currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { Ok(amount) } } /// This Unit struct represents MinorUnit in which core amount works #[derive( Default, Debug, serde::Deserialize, AsExpression, serde::Serialize, Clone, Copy, PartialEq, Eq, Hash, ToSchema, PartialOrd, Ord, )] #[diesel(sql_type = sql_types::BigInt)] pub struct MinorUnit(i64); impl MinorUnit { /// gets amount as i64 value will be removed in future pub fn get_amount_as_i64(self) -> i64 { self.0 } /// forms a new minor default unit i.e zero pub fn zero() -> Self { Self(0) } /// forms a new minor unit from amount pub fn new(value: i64) -> Self { Self(value) } /// checks if the amount is greater than the given value pub fn is_greater_than(&self, value: i64) -> bool { self.get_amount_as_i64() > value } /// Convert the amount to its major denomination based on Currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ fn to_major_unit_as_string( self, currency: enums::Currency, ) -> Result<StringMajorUnit, error_stack::Report<ParsingError>> { let amount_f64 = self.to_major_unit_as_f64(currency)?; let amount_string = if currency.is_zero_decimal_currency() { amount_f64.0.to_string() } else if currency.is_three_decimal_currency() { format!("{:.3}", amount_f64.0) } else { format!("{:.2}", amount_f64.0) }; Ok(StringMajorUnit::new(amount_string)) } /// Convert the amount to its major denomination based on Currency and return f64 fn to_major_unit_as_f64( self, currency: enums::Currency, ) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> { let amount_decimal = Decimal::from_i64(self.0).ok_or(ParsingError::I64ToDecimalConversionFailure)?; let amount = if currency.is_zero_decimal_currency() { amount_decimal } else if currency.is_three_decimal_currency() { amount_decimal / Decimal::from(1000) } else { amount_decimal / Decimal::from(100) }; let amount_f64 = amount .to_f64() .ok_or(ParsingError::FloatToDecimalConversionFailure)?; Ok(FloatMajorUnit::new(amount_f64)) } ///Convert minor unit to string minor unit fn to_minor_unit_as_string(self) -> Result<StringMinorUnit, error_stack::Report<ParsingError>> { Ok(StringMinorUnit::new(self.0.to_string())) } } impl From<NonZeroI64> for MinorUnit { fn from(val: NonZeroI64) -> Self { Self::new(val.get()) } } impl Display for MinorUnit { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl<DB> FromSql<sql_types::BigInt, DB> for MinorUnit where DB: Backend, i64: FromSql<sql_types::BigInt, DB>, { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = i64::from_sql(value)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::BigInt, DB> for MinorUnit where DB: Backend, i64: ToSql<sql_types::BigInt, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> Queryable<sql_types::BigInt, DB> for MinorUnit where DB: Backend, Self: FromSql<sql_types::BigInt, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl Add for MinorUnit { type Output = Self; fn add(self, a2: Self) -> Self { Self(self.0 + a2.0) } } impl Sub for MinorUnit { type Output = Self; fn sub(self, a2: Self) -> Self { Self(self.0 - a2.0) } } impl Mul<u16> for MinorUnit { type Output = Self; fn mul(self, a2: u16) -> Self::Output { Self(self.0 * i64::from(a2)) } } impl Sum for MinorUnit { fn sum<I: Iterator<Item = Self>>(iter: I) -> Self { iter.fold(Self(0), |a, b| a + b) } } /// Connector specific types to send #[derive( Default, Debug, serde::Deserialize, AsExpression, serde::Serialize, Clone, PartialEq, Eq, Hash, ToSchema, PartialOrd, )] #[diesel(sql_type = sql_types::Text)] pub struct StringMinorUnit(String); impl StringMinorUnit { /// forms a new minor unit in string from amount fn new(value: String) -> Self { Self(value) } /// converts to minor unit i64 from minor unit string value fn to_minor_unit_as_i64(&self) -> Result<MinorUnit, error_stack::Report<ParsingError>> { let amount_string = &self.0; let amount_decimal = Decimal::from_str(amount_string).map_err(|e| { ParsingError::StringToDecimalConversionFailure { error: e.to_string(), } })?; let amount_i64 = amount_decimal .to_i64() .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } } impl Display for StringMinorUnit { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl<DB> FromSql<sql_types::Text, DB> for StringMinorUnit where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(value)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::Text, DB> for StringMinorUnit where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> Queryable<sql_types::Text, DB> for StringMinorUnit where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } /// Connector specific types to send #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct FloatMajorUnit(f64); impl FloatMajorUnit { /// forms a new major unit from amount fn new(value: f64) -> Self { Self(value) } /// forms a new major unit with zero amount pub fn zero() -> Self { Self(0.0) } /// converts to minor unit as i64 from FloatMajorUnit fn to_minor_unit_as_i64( self, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { let amount_decimal = Decimal::from_f64(self.0).ok_or(ParsingError::FloatToDecimalConversionFailure)?; let amount = if currency.is_zero_decimal_currency() { amount_decimal } else if currency.is_three_decimal_currency() { amount_decimal * Decimal::from(1000) } else { amount_decimal * Decimal::from(100) }; let amount_i64 = amount .to_i64() .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } } /// Connector specific types to send #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)] pub struct StringMajorUnit(String); impl StringMajorUnit { /// forms a new major unit from amount fn new(value: String) -> Self { Self(value) } /// Converts to minor unit as i64 from StringMajorUnit fn to_minor_unit_as_i64( &self, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { let amount_decimal = Decimal::from_str(&self.0).map_err(|e| { ParsingError::StringToDecimalConversionFailure { error: e.to_string(), } })?; let amount = if currency.is_zero_decimal_currency() { amount_decimal } else if currency.is_three_decimal_currency() { amount_decimal * Decimal::from(1000) } else { amount_decimal * Decimal::from(100) }; let amount_i64 = amount .to_i64() .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } /// forms a new StringMajorUnit default unit i.e zero pub fn zero() -> Self { Self("0".to_string()) } /// Get string amount from struct to be removed in future pub fn get_amount_as_string(&self) -> String { self.0.clone() } /// forms a new default 2-decimal major unit pub fn zero_decimal() -> Self { Self("0.00".to_string()) } } #[derive( Debug, serde::Deserialize, AsExpression, serde::Serialize, Clone, PartialEq, Eq, Hash, ToSchema, PartialOrd, )] #[diesel(sql_type = sql_types::Text)] /// This domain type can be used for any url pub struct Url(url::Url); impl Url { /// Get string representation of the url pub fn get_string_repr(&self) -> &str { self.0.as_str() } /// wrap the url::Url in Url type pub fn wrap(url: url::Url) -> Self { Self(url) } /// Get the inner url pub fn into_inner(self) -> url::Url { self.0 } /// Add query params to the url pub fn add_query_params(mut self, (key, value): (&str, &str)) -> Self { let url = self .0 .query_pairs_mut() .append_pair(key, value) .finish() .clone(); Self(url) } } impl<DB> ToSql<sql_types::Text, DB> for Url where DB: Backend, str: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { let url_string = self.0.as_str(); url_string.to_sql(out) } } impl<DB> FromSql<sql_types::Text, DB> for Url where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(value)?; let url = url::Url::parse(&val)?; Ok(Self(url)) } } /// A type representing a range of time for filtering, including a mandatory start time and an optional end time. #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, )] pub struct TimeRange { /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed #[serde(with = "crate::custom_serde::iso8601")] #[serde(alias = "startTime")] pub start_time: PrimitiveDateTime, /// The end time to filter payments list or to get list of filters. If not passed the default time is now #[serde(default, with = "crate::custom_serde::iso8601::option")] #[serde(alias = "endTime")] pub end_time: Option<PrimitiveDateTime>, } #[cfg(test)] mod amount_conversion_tests { use super::*; const TWO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::USD; const THREE_DECIMAL_CURRENCY: enums::Currency = enums::Currency::BHD; const ZERO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::JPY; #[test] fn amount_conversion_to_float_major_unit() { let request_amount = MinorUnit::new(999999999); let required_conversion = FloatMajorUnitForConnector; // Two decimal currency conversions let converted_amount = required_conversion .convert(request_amount, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, 9999999.99); let converted_back_amount = required_conversion .convert_back(converted_amount, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Three decimal currency conversions let converted_amount = required_conversion .convert(request_amount, THREE_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, 999999.999); let converted_back_amount = required_conversion .convert_back(converted_amount, THREE_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Zero decimal currency conversions let converted_amount = required_conversion .convert(request_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, 999999999.0); let converted_back_amount = required_conversion .convert_back(converted_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); } #[test] fn amount_conversion_to_string_major_unit() { let request_amount = MinorUnit::new(999999999); let required_conversion = StringMajorUnitForConnector; // Two decimal currency conversions let converted_amount_two_decimal_currency = required_conversion .convert(request_amount, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!( converted_amount_two_decimal_currency.0, "9999999.99".to_string() ); let converted_back_amount = required_conversion .convert_back(converted_amount_two_decimal_currency, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Three decimal currency conversions let converted_amount_three_decimal_currency = required_conversion .convert(request_amount, THREE_DECIMAL_CURRENCY) .unwrap(); assert_eq!( converted_amount_three_decimal_currency.0, "999999.999".to_string() ); let converted_back_amount = required_conversion .convert_back( converted_amount_three_decimal_currency, THREE_DECIMAL_CURRENCY, ) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Zero decimal currency conversions let converted_amount = required_conversion .convert(request_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, "999999999".to_string()); let converted_back_amount = required_conversion .convert_back(converted_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); } #[test] fn amount_conversion_to_string_minor_unit() { let request_amount = MinorUnit::new(999999999); let currency = TWO_DECIMAL_CURRENCY; let required_conversion = StringMinorUnitForConnector; let converted_amount = required_conversion .convert(request_amount, currency) .unwrap(); assert_eq!(converted_amount.0, "999999999".to_string()); let converted_back_amount = required_conversion .convert_back(converted_amount, currency) .unwrap(); assert_eq!(converted_back_amount, request_amount); } } // Charges structs #[derive( Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] /// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details. pub struct ChargeRefunds { /// Identifier for charge created for the payment pub charge_id: String, /// Toggle for reverting the application fee that was collected for the payment. /// If set to false, the funds are pulled from the destination account. pub revert_platform_fee: Option<bool>, /// Toggle for reverting the transfer that was made during the charge. /// If set to false, the funds are pulled from the main platform's account. pub revert_transfer: Option<bool>, } crate::impl_to_sql_from_sql_json!(ChargeRefunds); /// A common type of domain type that can be used for fields that contain a string with restriction of length #[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub(crate) struct LengthString<const MAX_LENGTH: u16, const MIN_LENGTH: u16>(String); /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum LengthStringError { #[error("the maximum allowed length for this field is {0}")] /// Maximum length of string violated MaxLengthViolated(u16), #[error("the minimum required length for this field is {0}")] /// Minimum length of string violated MinLengthViolated(u16), } impl<const MAX_LENGTH: u16, const MIN_LENGTH: u16> LengthString<MAX_LENGTH, MIN_LENGTH> { /// Generates new [MerchantReferenceId] from the given input string pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthStringError> { let trimmed_input_string = input_string.trim().to_string(); let length_of_input_string = u16::try_from(trimmed_input_string.len()) .map_err(|_| LengthStringError::MaxLengthViolated(MAX_LENGTH))?; when(length_of_input_string > MAX_LENGTH, || { Err(LengthStringError::MaxLengthViolated(MAX_LENGTH)) })?; when(length_of_input_string < MIN_LENGTH, || { Err(LengthStringError::MinLengthViolated(MIN_LENGTH)) })?; Ok(Self(trimmed_input_string)) } pub(crate) fn new_unchecked(input_string: String) -> Self { Self(input_string) } } impl<'de, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Deserialize<'de> for LengthString<MAX_LENGTH, MIN_LENGTH> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from(deserialized_string.into()).map_err(serde::de::Error::custom) } } impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> FromSql<sql_types::Text, DB> for LengthString<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self(val)) } } impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> ToSql<sql_types::Text, DB> for LengthString<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Queryable<sql_types::Text, DB> for LengthString<MAX_LENGTH, MIN_LENGTH> where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } /// Domain type for description #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub struct Description(LengthString<MAX_DESCRIPTION_LENGTH, 1>); impl Description { /// Create a new Description Domain type without any length check from a static str pub fn from_str_unchecked(input_str: &'static str) -> Self { Self(LengthString::new_unchecked(input_str.to_owned())) } // TODO: Remove this function in future once description in router data is updated to domain type /// Get the string representation of the description pub fn get_string_repr(&self) -> &str { &self.0 .0 } } /// Domain type for Statement Descriptor #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub struct StatementDescriptor(LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>); impl<DB> Queryable<sql_types::Text, DB> for Description where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for Description where DB: Backend, LengthString<MAX_DESCRIPTION_LENGTH, 1>: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = LengthString::<MAX_DESCRIPTION_LENGTH, 1>::from_sql(bytes)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::Text, DB> for Description where DB: Backend, LengthString<MAX_DESCRIPTION_LENGTH, 1>: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> Queryable<sql_types::Text, DB> for StatementDescriptor where DB: Backend,
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/macros.rs
crates/common_utils/src/macros.rs
//! Utility macros #[allow(missing_docs)] #[macro_export] macro_rules! newtype_impl { ($is_pub:vis, $name:ident, $ty_path:path) => { impl core::ops::Deref for $name { type Target = $ty_path; fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for $name { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<$ty_path> for $name { fn from(ty: $ty_path) -> Self { Self(ty) } } impl $name { pub fn into_inner(self) -> $ty_path { self.0 } } }; } #[allow(missing_docs)] #[macro_export] macro_rules! newtype { ($is_pub:vis $name:ident = $ty_path:path) => { $is_pub struct $name(pub $ty_path); $crate::newtype_impl!($is_pub, $name, $ty_path); }; ($is_pub:vis $name:ident = $ty_path:path, derives = ($($trt:path),*)) => { #[derive($($trt),*)] $is_pub struct $name(pub $ty_path); $crate::newtype_impl!($is_pub, $name, $ty_path); }; } /// Use this to ensure that the corresponding /// openapi route has been implemented in the openapi crate #[macro_export] macro_rules! openapi_route { ($route_name: ident) => {{ #[cfg(feature = "openapi")] use openapi::routes::$route_name as _; $route_name }}; } #[allow(missing_docs)] #[macro_export] macro_rules! fallback_reverse_lookup_not_found { ($a:expr,$b:expr) => { match $a { Ok(res) => res, Err(err) => { router_env::logger::error!(reverse_lookup_fallback = ?err); match err.current_context() { errors::StorageError::ValueNotFound(_) => return $b, errors::StorageError::DatabaseError(data_err) => { match data_err.current_context() { diesel_models::errors::DatabaseError::NotFound => return $b, _ => return Err(err) } } _=> return Err(err) } } }; }; } /// Collects names of all optional fields that are `None`. /// This is typically useful for constructing error messages including a list of all missing fields. #[macro_export] macro_rules! collect_missing_value_keys { [$(($key:literal, $option:expr)),+] => { { let mut keys: Vec<&'static str> = Vec::new(); $( if $option.is_none() { keys.push($key); } )* keys } }; } /// Implements the `ToSql` and `FromSql` traits on a type to allow it to be serialized/deserialized /// to/from JSON data in the database. #[macro_export] macro_rules! impl_to_sql_from_sql_json { ($type:ty, $diesel_type:ty) => { #[allow(unused_qualifications)] impl diesel::serialize::ToSql<$diesel_type, diesel::pg::Pg> for $type { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { let value = serde_json::to_value(self)?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as diesel::serialize::ToSql< $diesel_type, diesel::pg::Pg, >>::to_sql(&value, &mut out.reborrow()) } } #[allow(unused_qualifications)] impl diesel::deserialize::FromSql<$diesel_type, diesel::pg::Pg> for $type { fn from_sql( bytes: <diesel::pg::Pg as diesel::backend::Backend>::RawValue<'_>, ) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< $diesel_type, diesel::pg::Pg, >>::from_sql(bytes)?; Ok(serde_json::from_value(value)?) } } }; ($type: ty) => { $crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Json); $crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Jsonb); }; } mod id_type { /// Defines an ID type. #[macro_export] macro_rules! id_type { ($type:ident, $doc:literal, $diesel_type:ty, $max_length:expr, $min_length:expr) => { #[doc = $doc] #[derive( Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, utoipa::ToSchema, )] #[diesel(sql_type = $diesel_type)] #[schema(value_type = String)] pub struct $type($crate::id_type::LengthId<$max_length, $min_length>); }; ($type:ident, $doc:literal) => { $crate::id_type!( $type, $doc, diesel::sql_types::Text, { $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH }, { $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH } ); }; } /// Defines a Global Id type #[cfg(feature = "v2")] #[macro_export] macro_rules! global_id_type { ($type:ident, $doc:literal) => { #[doc = $doc] #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct $type($crate::id_type::global_id::GlobalId); }; } /// Implements common methods on the specified ID type. #[macro_export] macro_rules! impl_id_type_methods { ($type:ty, $field_name:literal) => { impl $type { /// Get the string representation of the ID type. pub fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } }; } /// Implements the `Debug` trait on the specified ID type. #[macro_export] macro_rules! impl_debug_id_type { ($type:ty) => { impl core::fmt::Debug for $type { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple(stringify!($type)) .field(&self.0 .0 .0) .finish() } } }; } /// Implements the `TryFrom<Cow<'static, str>>` trait on the specified ID type. #[macro_export] macro_rules! impl_try_from_cow_str_id_type { ($type:ty, $field_name:literal) => { impl TryFrom<std::borrow::Cow<'static, str>> for $type { type Error = error_stack::Report<$crate::errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { use error_stack::ResultExt; let merchant_ref_id = $crate::id_type::LengthId::from(value).change_context( $crate::errors::ValidationError::IncorrectValueProvided { field_name: $field_name, }, )?; Ok(Self(merchant_ref_id)) } } }; } /// Implements the `Default` trait on the specified ID type. #[macro_export] macro_rules! impl_default_id_type { ($type:ty, $prefix:literal) => { impl Default for $type { fn default() -> Self { Self($crate::generate_ref_id_with_default_length($prefix)) } } }; } /// Implements the `GenerateId` trait on the specified ID type. #[macro_export] macro_rules! impl_generate_id_id_type { ($type:ty, $prefix:literal) => { impl $crate::id_type::GenerateId for $type { fn generate() -> Self { Self($crate::generate_ref_id_with_default_length($prefix)) } } }; } /// Implements the `SerializableSecret` trait on the specified ID type. #[macro_export] macro_rules! impl_serializable_secret_id_type { ($type:ty) => { impl masking::SerializableSecret for $type {} }; } /// Implements the `ToSql` and `FromSql` traits on the specified ID type. #[macro_export] macro_rules! impl_to_sql_from_sql_id_type { ($type:ty, $diesel_type:ty, $max_length:expr, $min_length:expr) => { impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::LengthId<$max_length, $min_length>: diesel::serialize::ToSql<$diesel_type, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::LengthId<$max_length, $min_length>: diesel::deserialize::FromSql<$diesel_type, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { $crate::id_type::LengthId::<$max_length, $min_length>::from_sql(value).map(Self) } } }; ($type:ty) => { $crate::impl_to_sql_from_sql_id_type!( $type, diesel::sql_types::Text, { $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH }, { $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH } ); }; } #[cfg(feature = "v2")] /// Implements the `ToSql` and `FromSql` traits on the specified Global ID type. #[macro_export] macro_rules! impl_to_sql_from_sql_global_id_type { ($type:ty, $diesel_type:ty) => { impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::global_id::GlobalId: diesel::serialize::ToSql<$diesel_type, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::global_id::GlobalId: diesel::deserialize::FromSql<$diesel_type, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { $crate::id_type::global_id::GlobalId::from_sql(value).map(Self) } } }; ($type:ty) => { $crate::impl_to_sql_from_sql_global_id_type!($type, diesel::sql_types::Text); }; } /// Implements the `Queryable` trait on the specified ID type. #[macro_export] macro_rules! impl_queryable_id_type { ($type:ty, $diesel_type:ty) => { impl<DB> diesel::Queryable<$diesel_type, DB> for $type where DB: diesel::backend::Backend, Self: diesel::deserialize::FromSql<$diesel_type, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } }; ($type:ty) => { $crate::impl_queryable_id_type!($type, diesel::sql_types::Text); }; } } /// Create new generic list wrapper #[macro_export] macro_rules! create_list_wrapper { ( $wrapper_name:ident, $type_name: ty, impl_functions: { $($function_def: tt)* } ) => { #[derive(Clone, Debug)] pub struct $wrapper_name(Vec<$type_name>); impl $wrapper_name { pub fn new(list: Vec<$type_name>) -> Self { Self(list) } pub fn with_capacity(size: usize) -> Self { Self(Vec::with_capacity(size)) } $($function_def)* } impl std::ops::Deref for $wrapper_name { type Target = Vec<$type_name>; fn deref(&self) -> &<Self as std::ops::Deref>::Target { &self.0 } } impl std::ops::DerefMut for $wrapper_name { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl IntoIterator for $wrapper_name { type Item = $type_name; type IntoIter = std::vec::IntoIter<$type_name>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl<'a> IntoIterator for &'a $wrapper_name { type Item = &'a $type_name; type IntoIter = std::slice::Iter<'a, $type_name>; fn into_iter(self) -> Self::IntoIter { self.0.iter() } } impl FromIterator<$type_name> for $wrapper_name { fn from_iter<T: IntoIterator<Item = $type_name>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } }; } /// Get the type name for a type #[macro_export] macro_rules! type_name { ($type:ty) => { std::any::type_name::<$type>() .rsplit("::") .nth(1) .unwrap_or_default(); }; } /// **Note** Creates an enum wrapper that implements `FromStr`, `Display`, `Serialize`, and `Deserialize` /// based on a specific string representation format: `"VariantName<delimiter>FieldValue"`. /// It handles parsing errors by returning a dedicated `Invalid` variant. /// *Note*: The macro adds `Invalid,` automatically. /// /// # Use Case /// /// This macro is designed for scenarios where you need an enum, with each variant /// holding a single piece of associated data, to be easily convertible to and from /// a simple string format. This is useful for cases where enum is serialized to key value pairs /// /// It avoids more complex serialization structures (like JSON objects `{"VariantName": value}`) /// in favor of a plain string representation. /// /// # Input Enum Format and Constraints /// /// To use this macro, the enum definition must adhere to the following structure: /// /// 1. **Public Enum:** The enum must be declared as `pub enum EnumName { ... }`. /// 2. **Struct Variants Only:** All variants must be struct variants (using `{}`). /// 3. **Exactly One Field:** Each struct variant must contain *exactly one* named field. /// * **Valid:** `VariantA { value: i32 }` /// * **Invalid:** `VariantA(i32)` (tuple variant) /// * **Invalid:** `VariantA` or `VariantA {}` (no field) /// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields) /// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimiter` literal, /// which is the character used to separate the variant name from the field data in /// the string representation (e.g., `tag_delimiter = ":",`). /// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`) /// must implement: /// * `core::str::FromStr`: To parse the field's data from the string part. /// The `Err` type should ideally be convertible to a meaningful error, though the /// macro currently uses a generic error message upon failure. /// * `core::fmt::Display`: To convert the field's data into the string part. /// * `serde::Serialize` and `serde::Deserialize<'de>`: Although the macro implements /// custom `Serialize`/`Deserialize` for the *enum* using the string format, the field /// type itself must satisfy these bounds if required elsewhere or by generic contexts. /// The macro's implementations rely solely on `Display` and `FromStr` for the conversion. /// 6. **Error Type:** This macro uses `core::convert::Infallible` as it never fails but gives /// `Self::Invalid` variant. /// /// # Serialization and Deserialization (`serde`) /// /// When `serde` features are enabled and the necessary traits are derived or implemented, /// this macro implements `Serialize` and `Deserialize` for the enum: /// /// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimiter = ":",`) /// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results /// in a JSON string: `"\"VariantA:123\""`. /// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`. /// It uses the enum's `FromStr` implementation internally. When deserializing from JSON, it /// expects a JSON string containing the correctly formatted value (e.g., `"\"VariantA:123\""`). /// /// # `Display` and `FromStr` /// /// **`Display`:** Formats valid variants to `"VariantName<delimiter>FieldValue"` and catch-all cases to `"Invalid"`. /// **`FromStr`:** Parses `"VariantName<delimiter>FieldValue"` to the variant, or returns `Self::Invalid` /// if the input string is malformed or `"Invalid"`. /// /// # Example /// /// ```rust /// use std::str::FromStr; /// /// crate::impl_enum_str!( /// tag_delimiter = ":", /// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed /// pub enum Setting { /// Timeout { duration_ms: u32 }, /// Username { name: String }, /// } /// ); /// // Note: The macro adds `Invalid,` automatically. /// /// fn main() { /// // Display /// let setting1 = Setting::Timeout { duration_ms: 5000 }; /// assert_eq!(setting1.to_string(), "Timeout:5000"); /// assert_eq!(Setting::Invalid.to_string(), "Invalid"); /// /// // FromStr (returns Self, not Result) /// let parsed_setting: Setting = "Username:admin".parse().expect("Valid parse"); // parse() itself doesn't panic /// assert_eq!(parsed_setting, Setting::Username { name: "admin".to_string() }); /// /// let invalid_format: Setting = "Timeout".parse().expect("Parse always returns Self"); /// assert_eq!(invalid_format, Setting::Invalid); // Malformed input yields Invalid /// /// let bad_data: Setting = "Timeout:fast".parse().expect("Parse always returns Self"); /// assert_eq!(bad_data, Setting::Invalid); // Bad field data yields Invalid /// /// let unknown_tag: Setting = "Unknown:abc".parse().expect("Parse always returns Self"); /// assert_eq!(unknown_tag, Setting::Invalid); // Unknown tag yields Invalid /// /// let explicit_invalid: Setting = "Invalid".parse().expect("Parse always returns Self"); /// assert_eq!(explicit_invalid, Setting::Invalid); // "Invalid" string yields Invalid /// /// // Serde (requires derive Serialize/Deserialize on Setting) /// // let json_output = serde_json::to_string(&setting1).unwrap(); /// // assert_eq!(json_output, "\"Timeout:5000\""); /// // let invalid_json_output = serde_json::to_string(&Setting::Invalid).unwrap(); /// // assert_eq!(invalid_json_output, "\"Invalid\""); /// /// // let deserialized: Setting = serde_json::from_str("\"Username:guest\"").unwrap(); /// // assert_eq!(deserialized, Setting::Username { name: "guest".to_string() }); /// // let deserialized_invalid: Setting = serde_json::from_str("\"Invalid\"").unwrap(); /// // assert_eq!(deserialized_invalid, Setting::Invalid); /// // let deserialized_malformed: Setting = serde_json::from_str("\"TimeoutFast\"").unwrap(); /// // assert_eq!(deserialized_malformed, Setting::Invalid); // Malformed -> Invalid /// } /// /// # // Mock macro definition for doctest purposes /// # #[macro_export] macro_rules! impl_enum_str { ($($tt:tt)*) => { $($tt)* } } /// ``` #[macro_export] macro_rules! impl_enum_str { ( tag_delimiter = $tag_delim:literal, $(#[$enum_attr:meta])* pub enum $enum_name:ident { $( $(#[$variant_attr:meta])* $variant:ident { $(#[$field_attr:meta])* $field:ident : $field_ty:ty $(,)? } ),* $(,)? } ) => { $(#[$enum_attr])* pub enum $enum_name { $( $(#[$variant_attr])* $variant { $(#[$field_attr])* $field : $field_ty }, )* /// Represents a parsing failure. Invalid, // Automatically add the Invalid variant } // Implement FromStr - now returns Self, not Result impl core::str::FromStr for $enum_name { // No associated error type needed type Err = core::convert::Infallible; // FromStr requires an Err type, use Infallible fn from_str(s: &str) -> Result<Self, Self::Err> { // Check for explicit "Invalid" string first if s == "Invalid" { #[cfg(feature = "logs")] router_env::logger::warn!( "Failed to parse {} enum from 'Invalid': explicit Invalid variant encountered", stringify!($enum_name) ); return Ok(Self::Invalid); } let Some((tag, associated_data)) = s.split_once($tag_delim) else { // Missing delimiter -> Invalid #[cfg(feature = "logs")] router_env::logger::warn!( "Failed to parse {} enum from '{}': missing delimiter", stringify!($enum_name), s ); return Ok(Self::Invalid); }; let result = match tag { $( stringify!($variant) => { // Try to parse the field data match associated_data.parse::<$field_ty>() { Ok(parsed_field) => { // Success -> construct the variant Self::$variant { $field: parsed_field } }, Err(_) => { // Field parse failure -> Invalid #[cfg(feature = "logs")] router_env::logger::warn!( "Failed to parse {} enum from '{}': field parse failure for variant '{}'", stringify!($enum_name), s, stringify!($variant) ); Self::Invalid } } } ),* // Unknown tag -> Invalid _ => { #[cfg(feature = "logs")] router_env::logger::warn!( "Failed to parse {} enum from '{}': unknown variant tag '{}'", stringify!($enum_name), s, tag ); Self::Invalid }, }; Ok(result) // Always Ok because failure modes return Self::Invalid } } // Implement Serialize impl ::serde::Serialize for $enum_name { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { match self { $( Self::$variant { $field } => { let s = format!("{}{}{}", stringify!($variant), $tag_delim, $field); serializer.serialize_str(&s) } )* // Handle Invalid variant Self::Invalid => serializer.serialize_str("Invalid"), } } } // Implement Deserialize impl<'de> ::serde::Deserialize<'de> for $enum_name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de>, { struct EnumVisitor; impl<'de> ::serde::de::Visitor<'de> for EnumVisitor { type Value = $enum_name; fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str(concat!("a string like VariantName", $tag_delim, "field_data or 'Invalid'")) } // Leverage the FromStr implementation which now returns Self::Invalid on failure fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: ::serde::de::Error, { // parse() now returns Result<Self, Infallible> // We unwrap() the Ok because it's infallible. Ok(value.parse::<$enum_name>().unwrap()) } fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: ::serde::de::Error, { Ok(value.parse::<$enum_name>().unwrap()) } } deserializer.deserialize_str(EnumVisitor) } } // Implement Display impl core::fmt::Display for $enum_name { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { $( Self::$variant { $field } => { write!(f, "{}{}{}", stringify!($variant), $tag_delim, $field) } )* // Handle Invalid variant Self::Invalid => write!(f, "Invalid"), } } } // Implement HasInvalidVariant trait impl $crate::types::HasInvalidVariant for $enum_name { fn is_invalid(&self) -> bool { matches!(self, Self::Invalid) } } }; } // --- Tests --- #[cfg(test)] mod tests { use serde_json::{json, Value as JsonValue}; impl_enum_str!( tag_delimiter = ":", #[derive(Debug, PartialEq, Clone)] pub enum TestEnum { VariantA { value: i32 }, VariantB { text: String }, VariantC { id: u64 }, VariantJson { data: JsonValue }, } // Note: Invalid variant is added automatically by the macro ); #[test] fn test_enum_from_str_ok() { // Success cases just parse directly let parsed_a: TestEnum = "VariantA:42".parse().unwrap(); // Unwrapping Infallible is fine assert_eq!(parsed_a, TestEnum::VariantA { value: 42 }); let parsed_b: TestEnum = "VariantB:hello world".parse().unwrap(); assert_eq!( parsed_b, TestEnum::VariantB { text: "hello world".to_string() } ); let parsed_c: TestEnum = "VariantC:123456789012345".parse().unwrap(); assert_eq!( parsed_c, TestEnum::VariantC { id: 123456789012345 } ); let parsed_json: TestEnum = r#"VariantJson:{"ok":true}"#.parse().unwrap(); assert_eq!( parsed_json, TestEnum::VariantJson { data: json!({"ok": true}) } ); } #[test] fn test_enum_from_str_failures_yield_invalid() { // Missing delimiter let parsed: TestEnum = "VariantA".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Unknown tag let parsed: TestEnum = "UnknownVariant:123".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Bad field data for i32 let parsed: TestEnum = "VariantA:not_a_number".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Bad field data for JsonValue let parsed: TestEnum = r#"VariantJson:{"bad_json"#.parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Empty field data for non-string (e.g., i32) let parsed: TestEnum = "VariantA:".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Empty field data for string IS valid for String type let parsed_str: TestEnum = "VariantB:".parse().unwrap(); assert_eq!( parsed_str, TestEnum::VariantB { text: "".to_string() } ); // Parsing the literal "Invalid" string let parsed_invalid_str: TestEnum = "Invalid".parse().unwrap(); assert_eq!(parsed_invalid_str, TestEnum::Invalid); } #[test] fn test_enum_display_and_serialize() { // Display valid let value_a = TestEnum::VariantA { value: 99 }; assert_eq!(value_a.to_string(), "VariantA:99"); // Serialize valid let json_a = serde_json::to_string(&value_a).expect("Serialize A failed"); assert_eq!(json_a, "\"VariantA:99\""); // Serializes to JSON string // Display Invalid let value_invalid = TestEnum::Invalid; assert_eq!(value_invalid.to_string(), "Invalid"); // Serialize Invalid let json_invalid = serde_json::to_string(&value_invalid).expect("Serialize Invalid failed"); assert_eq!(json_invalid, "\"Invalid\""); // Serializes to JSON string "Invalid" } #[test] fn test_enum_deserialize() { // Deserialize valid let input_a = "\"VariantA:123\""; let deserialized_a: TestEnum = serde_json::from_str(input_a).expect("Deserialize A failed"); assert_eq!(deserialized_a, TestEnum::VariantA { value: 123 }); // Deserialize explicit "Invalid" let input_invalid = "\"Invalid\""; let deserialized_invalid: TestEnum = serde_json::from_str(input_invalid).expect("Deserialize Invalid failed"); assert_eq!(deserialized_invalid, TestEnum::Invalid); // Deserialize malformed string (according to macro rules) -> Invalid let input_malformed = "\"VariantA_no_delimiter\""; let deserialized_malformed: TestEnum = serde_json::from_str(input_malformed).expect("Deserialize malformed should succeed"); assert_eq!(deserialized_malformed, TestEnum::Invalid); // Deserialize string with bad field data -> Invalid let input_bad_data = "\"VariantA:not_a_number\""; let deserialized_bad_data: TestEnum = serde_json::from_str(input_bad_data).expect("Deserialize bad data should succeed"); assert_eq!(deserialized_bad_data, TestEnum::Invalid); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/link_utils.rs
crates/common_utils/src/link_utils.rs
//! This module has common utilities for links in HyperSwitch use std::{collections::HashSet, primitive::i64}; use common_enums::{enums, UIWidgetFormLayout}; use diesel::{ backend::Backend, deserialize, deserialize::FromSql, serialize::{Output, ToSql}, sql_types::Jsonb, AsExpression, FromSqlRow, }; use error_stack::{report, ResultExt}; use masking::Secret; use regex::Regex; #[cfg(feature = "logs")] use router_env::logger; use serde::Serialize; use utoipa::ToSchema; use crate::{consts, errors::ParsingError, id_type, types::MinorUnit}; #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, )] #[serde(rename_all = "snake_case", tag = "type", content = "value")] #[diesel(sql_type = Jsonb)] /// Link status enum pub enum GenericLinkStatus { /// Status variants for payment method collect link PaymentMethodCollect(PaymentMethodCollectStatus), /// Status variants for payout link PayoutLink(PayoutLinkStatus), } impl Default for GenericLinkStatus { fn default() -> Self { Self::PaymentMethodCollect(PaymentMethodCollectStatus::Initiated) } } crate::impl_to_sql_from_sql_json!(GenericLinkStatus); #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, )] #[serde(rename_all = "snake_case")] #[diesel(sql_type = Jsonb)] /// Status variants for payment method collect links pub enum PaymentMethodCollectStatus { /// Link was initialized Initiated, /// Link was expired or invalidated Invalidated, /// Payment method details were submitted Submitted, } impl<DB: Backend> FromSql<Jsonb, DB> for PaymentMethodCollectStatus where serde_json::Value: FromSql<Jsonb, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; let generic_status: GenericLinkStatus = serde_json::from_value(value)?; match generic_status { GenericLinkStatus::PaymentMethodCollect(status) => Ok(status), GenericLinkStatus::PayoutLink(_) => Err(report!(ParsingError::EnumParseFailure( "PaymentMethodCollectStatus" ))) .attach_printable("Invalid status for PaymentMethodCollect")?, } } } impl ToSql<Jsonb, diesel::pg::Pg> for PaymentMethodCollectStatus where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, { // This wraps PaymentMethodCollectStatus with GenericLinkStatus // Required for storing the status in required format in DB (GenericLinkStatus) // This type is used in PaymentMethodCollectLink (a variant of GenericLink, used in the application for avoiding conversion of data and status) fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { let value = serde_json::to_value(GenericLinkStatus::PaymentMethodCollect(self.clone()))?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) } } #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, )] #[serde(rename_all = "snake_case")] #[diesel(sql_type = Jsonb)] /// Status variants for payout links pub enum PayoutLinkStatus { /// Link was initialized Initiated, /// Link was expired or invalidated Invalidated, /// Payout details were submitted Submitted, } impl<DB: Backend> FromSql<Jsonb, DB> for PayoutLinkStatus where serde_json::Value: FromSql<Jsonb, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; let generic_status: GenericLinkStatus = serde_json::from_value(value)?; match generic_status { GenericLinkStatus::PayoutLink(status) => Ok(status), GenericLinkStatus::PaymentMethodCollect(_) => { Err(report!(ParsingError::EnumParseFailure("PayoutLinkStatus"))) .attach_printable("Invalid status for PayoutLink")? } } } } impl ToSql<Jsonb, diesel::pg::Pg> for PayoutLinkStatus where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, { // This wraps PayoutLinkStatus with GenericLinkStatus // Required for storing the status in required format in DB (GenericLinkStatus) // This type is used in PayoutLink (a variant of GenericLink, used in the application for avoiding conversion of data and status) fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { let value = serde_json::to_value(GenericLinkStatus::PayoutLink(self.clone()))?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) } } #[derive(Serialize, serde::Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] /// Payout link object pub struct PayoutLinkData { /// Identifier for the payout link pub payout_link_id: String, /// Identifier for the customer pub customer_id: id_type::CustomerId, /// Identifier for the payouts resource pub payout_id: id_type::PayoutId, /// Link to render the payout link pub link: url::Url, /// Client secret generated for authenticating frontend APIs pub client_secret: Secret<String>, /// Expiry in seconds from the time it was created pub session_expiry: u32, #[serde(flatten)] /// Payout link's UI configurations pub ui_config: GenericLinkUiConfig, /// List of enabled payment methods pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>, /// Payout amount pub amount: MinorUnit, /// Payout currency pub currency: enums::Currency, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: HashSet<String>, /// Form layout of the payout link pub form_layout: Option<UIWidgetFormLayout>, /// `test_mode` can be used for testing payout links without any restrictions pub test_mode: Option<bool>, } crate::impl_to_sql_from_sql_json!(PayoutLinkData); /// Object for GenericLinkUiConfig #[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)] pub struct GenericLinkUiConfig { /// Merchant's display logo #[schema(value_type = Option<String>, max_length = 255, example = "https://hyperswitch.io/favicon.ico")] pub logo: Option<url::Url>, /// Custom merchant name for the link #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch")] pub merchant_name: Option<Secret<String>>, /// Primary color to be used in the form represented in hex format #[schema(value_type = Option<String>, max_length = 255, example = "#4285F4")] pub theme: Option<String>, } /// Object for GenericLinkUiConfigFormData #[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)] pub struct GenericLinkUiConfigFormData { /// Merchant's display logo #[schema(value_type = String, max_length = 255, example = "https://hyperswitch.io/favicon.ico")] pub logo: url::Url, /// Custom merchant name for the link #[schema(value_type = String, max_length = 255, example = "Hyperswitch")] pub merchant_name: Secret<String>, /// Primary color to be used in the form represented in hex format #[schema(value_type = String, max_length = 255, example = "#4285F4")] pub theme: String, } /// Object for EnabledPaymentMethod #[derive(Clone, Debug, Serialize, serde::Deserialize, ToSchema)] pub struct EnabledPaymentMethod { /// Payment method (banks, cards, wallets) enabled for the operation #[schema(value_type = PaymentMethod)] pub payment_method: enums::PaymentMethod, /// An array of associated payment method types #[schema(value_type = HashSet<PaymentMethodType>)] pub payment_method_types: HashSet<enums::PaymentMethodType>, } /// Util function for validating a domain without any wildcard characters. pub fn validate_strict_domain(domain: &str) -> bool { Regex::new(consts::STRICT_DOMAIN_REGEX) .map(|regex| regex.is_match(domain)) .map_err(|err| { let err_msg = format!("Invalid strict domain regex: {err:?}"); #[cfg(feature = "logs")] logger::error!(err_msg); err_msg }) .unwrap_or(false) } /// Util function for validating a domain with "*" wildcard characters. pub fn validate_wildcard_domain(domain: &str) -> bool { Regex::new(consts::WILDCARD_DOMAIN_REGEX) .map(|regex| regex.is_match(domain)) .map_err(|err| { let err_msg = format!("Invalid strict domain regex: {err:?}"); #[cfg(feature = "logs")] logger::error!(err_msg); err_msg }) .unwrap_or(false) } #[cfg(test)] mod domain_tests { use regex::Regex; use super::*; #[test] fn test_validate_strict_domain_regex() { assert!( Regex::new(consts::STRICT_DOMAIN_REGEX).is_ok(), "Strict domain regex is invalid" ); } #[test] fn test_validate_wildcard_domain_regex() { assert!( Regex::new(consts::WILDCARD_DOMAIN_REGEX).is_ok(), "Wildcard domain regex is invalid" ); } #[test] fn test_validate_strict_domain() { let valid_domains = vec![ "example.com", "example.subdomain.com", "https://example.com:8080", "http://example.com", "example.com:8080", "example.com:443", "localhost:443", "127.0.0.1:443", ]; for domain in valid_domains { assert!( validate_strict_domain(domain), "Could not validate strict domain: {domain}", ); } let invalid_domains = vec![ "", "invalid.domain.", "not_a_domain", "http://example.com/path?query=1#fragment", "127.0.0.1.2:443", ]; for domain in invalid_domains { assert!( !validate_strict_domain(domain), "Could not validate invalid strict domain: {domain}", ); } } #[test] fn test_validate_wildcard_domain() { let valid_domains = vec![ "example.com", "example.subdomain.com", "https://example.com:8080", "http://example.com", "example.com:8080", "example.com:443", "localhost:443", "127.0.0.1:443", "*.com", "example.*.com", "example.com:*", "*:443", "localhost:*", "127.0.0.*:*", "*:*", ]; for domain in valid_domains { assert!( validate_wildcard_domain(domain), "Could not validate wildcard domain: {domain}", ); } let invalid_domains = vec![ "", "invalid.domain.", "not_a_domain", "http://example.com/path?query=1#fragment", "*.", ".*", "example.com:*:", "*:443:", ":localhost:*", "127.00.*:*", ]; for domain in invalid_domains { assert!( !validate_wildcard_domain(domain), "Could not validate invalid wildcard domain: {domain}", ); } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/custom_serde.rs
crates/common_utils/src/custom_serde.rs
//! Custom serialization/deserialization implementations. /// Use the well-known ISO 8601 format when serializing and deserializing an /// [`PrimitiveDateTime`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod iso8601 { use std::num::NonZeroU8; use serde::{ser::Error as _, Deserializer, Serialize, Serializer}; use time::{ format_description::well_known::{ iso8601::{Config, EncodedConfig, TimePrecision}, Iso8601, }, serde::iso8601, PrimitiveDateTime, UtcOffset, }; const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(3), }) .encode(); /// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format. pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .assume_utc() .format(&Iso8601::<FORMAT_CONFIG>) .map_err(S::Error::custom)? .serialize(serializer) } /// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> where D: Deserializer<'a>, { iso8601::deserialize(deserializer).map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) } /// Use the well-known ISO 8601 format when serializing and deserializing an /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod option { use serde::Serialize; use time::format_description::well_known::Iso8601; use super::*; /// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format. pub fn serialize<S>( date_time: &Option<PrimitiveDateTime>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>)) .transpose() .map_err(S::Error::custom)? .serialize(serializer) } /// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> where D: Deserializer<'a>, { iso8601::option::deserialize(deserializer).map(|option_offset_date_time| { option_offset_date_time.map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) }) } } /// Use the well-known ISO 8601 format which is without timezone when serializing and deserializing an /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod option_without_timezone { use serde::{de, Deserialize, Serialize}; use time::macros::format_description; use super::*; /// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format which is without timezone. pub fn serialize<S>( date_time: &Option<PrimitiveDateTime>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .map(|date_time| { let format = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]"); date_time.assume_utc().format(format) }) .transpose() .map_err(S::Error::custom)? .serialize(serializer) } /// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> where D: Deserializer<'a>, { Option::deserialize(deserializer)? .map(|time_string| { let format = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]"); PrimitiveDateTime::parse(time_string, format).map_err(|_| { de::Error::custom(format!( "Failed to parse PrimitiveDateTime from {time_string}" )) }) }) .transpose() } } } /// Use the UNIX timestamp when serializing and deserializing an /// [`PrimitiveDateTime`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod timestamp { use serde::{Deserializer, Serialize, Serializer}; use time::{serde::timestamp, PrimitiveDateTime, UtcOffset}; /// Serialize a [`PrimitiveDateTime`] using UNIX timestamp. pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .assume_utc() .unix_timestamp() .serialize(serializer) } /// Deserialize an [`PrimitiveDateTime`] from UNIX timestamp. pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> where D: Deserializer<'a>, { timestamp::deserialize(deserializer).map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) } /// Use the UNIX timestamp when serializing and deserializing an /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod option { use serde::Serialize; use super::*; /// Serialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp. pub fn serialize<S>( date_time: &Option<PrimitiveDateTime>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .map(|date_time| date_time.assume_utc().unix_timestamp()) .serialize(serializer) } /// Deserialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp. pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> where D: Deserializer<'a>, { timestamp::option::deserialize(deserializer).map(|option_offset_date_time| { option_offset_date_time.map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) }) } } } /// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860> pub mod json_string { use serde::{ de::{self, Deserialize, DeserializeOwned, Deserializer}, ser::{self, Serialize, Serializer}, }; /// Serialize a type to json_string format pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error> where T: Serialize, S: Serializer, { let j = serde_json::to_string(value).map_err(ser::Error::custom)?; j.serialize(serializer) } /// Deserialize a string which is in json format pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: DeserializeOwned, D: Deserializer<'de>, { let j = String::deserialize(deserializer)?; serde_json::from_str(&j).map_err(de::Error::custom) } } /// Use a custom ISO 8601 format when serializing and deserializing /// [`PrimitiveDateTime`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod iso8601custom { use serde::{ser::Error as _, Deserializer, Serialize, Serializer}; use time::{ format_description::well_known::{ iso8601::{Config, EncodedConfig, TimePrecision}, Iso8601, }, serde::iso8601, PrimitiveDateTime, UtcOffset, }; const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT .set_time_precision(TimePrecision::Second { decimal_digits: None, }) .encode(); /// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format. pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .assume_utc() .format(&Iso8601::<FORMAT_CONFIG>) .map_err(S::Error::custom)? .replace('T', " ") .replace('Z', "") .serialize(serializer) } /// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> where D: Deserializer<'a>, { iso8601::deserialize(deserializer).map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use serde_json::json; #[test] fn test_leap_second_parse() { #[derive(Serialize, Deserialize)] struct Try { #[serde(with = "crate::custom_serde::iso8601")] f: time::PrimitiveDateTime, } let leap_second_date_time = json!({"f": "2023-12-31T23:59:60.000Z"}); let deser = serde_json::from_value::<Try>(leap_second_date_time); assert!(deser.is_ok()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/transformers.rs
crates/common_utils/src/transformers.rs
//! Utilities for converting between foreign types /// Trait for converting from one foreign type to another pub trait ForeignFrom<F> { /// Convert from a foreign type to the current type fn foreign_from(from: F) -> Self; } /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/events.rs
crates/common_utils/src/events.rs
use serde::Serialize; use crate::{id_type, types::TimeRange}; pub trait ApiEventMetric { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(tag = "flow_type", rename_all = "snake_case")] pub enum ApiEventsType { Payout { payout_id: id_type::PayoutId, }, #[cfg(feature = "v1")] Payment { payment_id: id_type::PaymentId, }, #[cfg(feature = "v2")] Payment { payment_id: id_type::GlobalPaymentId, }, #[cfg(feature = "v1")] Refund { payment_id: Option<id_type::PaymentId>, refund_id: String, }, #[cfg(feature = "v2")] Refund { payment_id: Option<id_type::GlobalPaymentId>, refund_id: id_type::GlobalRefundId, }, #[cfg(feature = "v1")] PaymentMethod { payment_method_id: String, payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, }, #[cfg(feature = "v2")] PaymentMethod { payment_method_id: id_type::GlobalPaymentMethodId, payment_method_type: Option<common_enums::PaymentMethod>, payment_method_subtype: Option<common_enums::PaymentMethodType>, }, #[cfg(feature = "v2")] PaymentMethodCreate, #[cfg(feature = "v2")] Customer { customer_id: Option<id_type::GlobalCustomerId>, }, #[cfg(feature = "v1")] Customer { customer_id: id_type::CustomerId, }, BusinessProfile { profile_id: id_type::ProfileId, }, ApiKey { key_id: id_type::ApiKeyId, }, User { user_id: String, }, PaymentMethodList { payment_id: Option<String>, }, #[cfg(feature = "v2")] PaymentMethodListForPaymentMethods { payment_method_id: id_type::GlobalPaymentMethodId, }, #[cfg(feature = "v1")] Webhooks { connector: String, payment_id: Option<id_type::PaymentId>, refund_id: Option<String>, }, #[cfg(feature = "v1")] NetworkTokenWebhook { payment_method_id: Option<String>, }, #[cfg(feature = "v2")] Webhooks { connector: id_type::MerchantConnectorAccountId, payment_id: Option<id_type::GlobalPaymentId>, refund_id: Option<id_type::GlobalRefundId>, }, Routing, Subscription, Invoice, ResourceListAPI, #[cfg(feature = "v1")] PaymentRedirectionResponse { connector: Option<String>, payment_id: Option<id_type::PaymentId>, }, #[cfg(feature = "v2")] PaymentRedirectionResponse { payment_id: id_type::GlobalPaymentId, }, Gsm, // TODO: This has to be removed once the corresponding apiEventTypes are created Miscellaneous, Keymanager, RustLocker, ApplePayCertificatesMigration, FraudCheck, Recon, ExternalServiceAuth, Dispute { dispute_id: String, }, Events { merchant_id: id_type::MerchantId, }, PaymentMethodCollectLink { link_id: String, }, Poll { poll_id: String, }, Analytics, #[cfg(feature = "v2")] ClientSecret { key_id: id_type::ClientSecretId, }, #[cfg(feature = "v2")] PaymentMethodSession { payment_method_session_id: id_type::GlobalPaymentMethodSessionId, }, #[cfg(feature = "v2")] Token { token_id: Option<id_type::GlobalTokenId>, }, ProcessTracker, Authentication { authentication_id: id_type::AuthenticationId, }, ProfileAcquirer { profile_acquirer_id: id_type::ProfileAcquirerId, }, ThreeDsDecisionRule, Chat, Oidc, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(tag = "api_flow", rename_all = "snake_case")] pub enum ConnectorEventsType { Payout { payout_id: String, }, Payment { payment_id: String, }, Refund { payment_id: String, refund_id: String, }, Dispute { dispute_id: String, }, } impl ConnectorEventsType { pub fn new( payment_id: String, refund_id: Option<String>, payout_id: Option<String>, dispute_id: Option<String>, ) -> Self { match (refund_id, payout_id, dispute_id) { (Some(refund_id), _, _) => Self::Refund { payment_id, refund_id, }, (_, Some(payout_id), _) => Self::Payout { payout_id }, (_, _, Some(dispute_id)) => Self::Dispute { dispute_id }, _ => Self::Payment { payment_id }, } } } impl ApiEventMetric for serde_json::Value {} impl ApiEventMetric for () {} #[cfg(feature = "v1")] impl ApiEventMetric for id_type::PaymentId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for id_type::PayoutId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for id_type::GlobalPaymentId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.clone(), }) } } impl<Q: ApiEventMetric, E> ApiEventMetric for Result<Q, E> { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self { Ok(q) => q.get_api_event_type(), Err(_) => None, } } } // TODO: Ideally all these types should be replaced by newtype responses impl<T> ApiEventMetric for Vec<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } #[macro_export] macro_rules! impl_api_event_type { ($event: ident, ($($type:ty),+))=> { $( impl ApiEventMetric for $type { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::$event) } } )+ }; } impl_api_event_type!( Miscellaneous, ( String, id_type::MerchantId, (Option<i64>, Option<i64>, String), (Option<i64>, Option<i64>, id_type::MerchantId), bool ) ); impl<T: ApiEventMetric> ApiEventMetric for &T { fn get_api_event_type(&self) -> Option<ApiEventsType> { T::get_api_event_type(self) } } impl ApiEventMetric for TimeRange {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/metrics.rs
crates/common_utils/src/metrics.rs
//! Utilities for metrics pub mod utils;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/request.rs
crates/common_utils/src/request.rs
use masking::{Maskable, Secret}; use reqwest::multipart::Form; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; pub type Headers = std::collections::HashSet<(String, Maskable<String>)>; #[derive( Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "UPPERCASE")] #[strum(serialize_all = "UPPERCASE")] pub enum Method { Get, Post, Put, Delete, Patch, } #[derive(Deserialize, Serialize, Debug)] pub enum ContentType { Json, FormUrlEncoded, FormData, Xml, } fn default_request_headers() -> [(String, Maskable<String>); 1] { use http::header; [(header::VIA.to_string(), "HyperSwitch".to_string().into())] } #[derive(Debug)] pub struct Request { pub url: String, pub headers: Headers, pub method: Method, pub certificate: Option<Secret<String>>, pub certificate_key: Option<Secret<String>>, pub body: Option<RequestContent>, pub ca_certificate: Option<Secret<String>>, } impl std::fmt::Debug for RequestContent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Json(_) => "JsonRequestBody", Self::FormUrlEncoded(_) => "FormUrlEncodedRequestBody", Self::FormData(_) => "FormDataRequestBody", Self::Xml(_) => "XmlRequestBody", Self::RawBytes(_) => "RawBytesRequestBody", }) } } pub enum RequestContent { Json(Box<dyn masking::ErasedMaskSerialize + Send>), FormUrlEncoded(Box<dyn masking::ErasedMaskSerialize + Send>), FormData((Form, Box<dyn masking::ErasedMaskSerialize + Send>)), Xml(Box<dyn masking::ErasedMaskSerialize + Send>), RawBytes(Vec<u8>), } impl RequestContent { pub fn get_inner_value(&self) -> Secret<String> { match self { Self::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(), Self::FormUrlEncoded(i) => serde_urlencoded::to_string(i).unwrap_or_default().into(), Self::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(), Self::FormData((_, i)) => serde_json::to_string(i).unwrap_or_default().into(), Self::RawBytes(_) => String::new().into(), } } } impl Request { pub fn new(method: Method, url: &str) -> Self { Self { method, url: String::from(url), headers: std::collections::HashSet::new(), certificate: None, certificate_key: None, body: None, ca_certificate: None, } } pub fn set_body<T: Into<RequestContent>>(&mut self, body: T) { self.body.replace(body.into()); } pub fn add_default_headers(&mut self) { self.headers.extend(default_request_headers()); } pub fn add_header(&mut self, header: &str, value: Maskable<String>) { self.headers.insert((String::from(header), value)); } pub fn add_certificate(&mut self, certificate: Option<Secret<String>>) { self.certificate = certificate; } pub fn add_certificate_key(&mut self, certificate_key: Option<Secret<String>>) { self.certificate = certificate_key; } } #[derive(Debug)] pub struct RequestBuilder { pub url: String, pub headers: Headers, pub method: Method, pub certificate: Option<Secret<String>>, pub certificate_key: Option<Secret<String>>, pub body: Option<RequestContent>, pub ca_certificate: Option<Secret<String>>, } impl RequestBuilder { pub fn new() -> Self { Self { method: Method::Get, url: String::with_capacity(1024), headers: std::collections::HashSet::new(), certificate: None, certificate_key: None, body: None, ca_certificate: None, } } pub fn url(mut self, url: &str) -> Self { self.url = url.into(); self } pub fn method(mut self, method: Method) -> Self { self.method = method; self } pub fn attach_default_headers(mut self) -> Self { self.headers.extend(default_request_headers()); self } pub fn header(mut self, header: &str, value: &str) -> Self { self.headers.insert((header.into(), value.into())); self } pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self { self.headers.extend(headers); self } pub fn set_optional_body<T: Into<RequestContent>>(mut self, body: Option<T>) -> Self { body.map(|body| self.body.replace(body.into())); self } pub fn set_body<T: Into<RequestContent>>(mut self, body: T) -> Self { self.body.replace(body.into()); self } pub fn add_certificate(mut self, certificate: Option<Secret<String>>) -> Self { self.certificate = certificate; self } pub fn add_certificate_key(mut self, certificate_key: Option<Secret<String>>) -> Self { self.certificate_key = certificate_key; self } pub fn add_ca_certificate_pem(mut self, ca_certificate: Option<Secret<String>>) -> Self { self.ca_certificate = ca_certificate; self } pub fn build(self) -> Request { Request { method: self.method, url: self.url, headers: self.headers, certificate: self.certificate, certificate_key: self.certificate_key, body: self.body, ca_certificate: self.ca_certificate, } } } impl Default for RequestBuilder { fn default() -> Self { Self::new() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/crypto.rs
crates/common_utils/src/crypto.rs
//! Utilities for cryptographic algorithms use std::ops::Deref; use base64::Engine; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use ring::{ aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey}, hmac, rand as ring_rand, signature::{RsaKeyPair, RSA_PSS_SHA256}, }; #[cfg(feature = "logs")] use router_env::logger; use rsa::{ pkcs1::DecodeRsaPrivateKey, pkcs8::{DecodePrivateKey, DecodePublicKey}, signature::Verifier, traits::PublicKeyParts, }; use crate::{ consts::{BASE64_ENGINE, BASE64_ENGINE_URL_SAFE_NO_PAD}, errors::{self, CustomResult}, pii::{self, EncryptionStrategy}, }; #[derive(Clone, Debug)] struct NonceSequence(u128); impl NonceSequence { /// Byte index at which sequence number starts in a 16-byte (128-bit) sequence. /// This byte index considers the big endian order used while encoding and decoding the nonce /// to/from a 128-bit unsigned integer. const SEQUENCE_NUMBER_START_INDEX: usize = 4; /// Generate a random nonce sequence. fn new() -> Result<Self, ring::error::Unspecified> { use ring::rand::{SecureRandom, SystemRandom}; let rng = SystemRandom::new(); // 96-bit sequence number, stored in a 128-bit unsigned integer in big-endian order let mut sequence_number = [0_u8; 128 / 8]; rng.fill(&mut sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..])?; let sequence_number = u128::from_be_bytes(sequence_number); Ok(Self(sequence_number)) } /// Returns the current nonce value as bytes. fn current(&self) -> [u8; aead::NONCE_LEN] { let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); nonce } /// Constructs a nonce sequence from bytes fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self { let mut sequence_number = [0_u8; 128 / 8]; sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes); let sequence_number = u128::from_be_bytes(sequence_number); Self(sequence_number) } } impl aead::NonceSequence for NonceSequence { fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> { let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); // Increment sequence number self.0 = self.0.wrapping_add(1); // Return previous sequence number as bytes Ok(aead::Nonce::assume_unique_for_key(nonce)) } } /// Trait for cryptographically signing messages pub trait SignMessage { /// Takes in a secret and a message and returns the calculated signature as bytes fn sign_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Trait for cryptographically verifying a message against a signature pub trait VerifySignature { /// Takes in a secret, the signature and the message and verifies the message /// against the signature fn verify_signature( &self, _secret: &[u8], _signature: &[u8], _msg: &[u8], ) -> CustomResult<bool, errors::CryptoError>; } /// Trait for cryptographically encoding a message pub trait EncodeMessage { /// Takes in a secret and the message and encodes it, returning bytes fn encode_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Trait for cryptographically decoding a message pub trait DecodeMessage { /// Takes in a secret, an encoded messages and attempts to decode it, returning bytes fn decode_message( &self, _secret: &[u8], _msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Represents no cryptographic algorithm. /// Implements all crypto traits and acts like a Nop #[derive(Debug)] pub struct NoAlgorithm; impl SignMessage for NoAlgorithm { fn sign_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(Vec::new()) } } impl VerifySignature for NoAlgorithm { fn verify_signature( &self, _secret: &[u8], _signature: &[u8], _msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { Ok(true) } } impl EncodeMessage for NoAlgorithm { fn encode_message( &self, _secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(msg.to_vec()) } } impl DecodeMessage for NoAlgorithm { fn decode_message( &self, _secret: &[u8], msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(msg.expose()) } } /// Represents the HMAC-SHA-1 algorithm #[derive(Debug)] pub struct HmacSha1; impl SignMessage for HmacSha1 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha1 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Represents the HMAC-SHA-256 algorithm #[derive(Debug)] pub struct HmacSha256; impl SignMessage for HmacSha256 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA256, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha256 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA256, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Represents the HMAC-SHA-512 algorithm #[derive(Debug)] pub struct HmacSha512; impl SignMessage for HmacSha512 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA512, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha512 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA512, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Blake3 #[derive(Debug)] pub struct Blake3(String); impl Blake3 { /// Create a new instance of Blake3 with a key pub fn new(key: impl Into<String>) -> Self { Self(key.into()) } } impl SignMessage for Blake3 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = blake3::derive_key(&self.0, secret); let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec(); Ok(output) } } impl VerifySignature for Blake3 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = blake3::derive_key(&self.0, secret); let output = blake3::keyed_hash(&key, msg); Ok(output.as_bytes() == signature) } } /// Represents the GCM-AES-256 algorithm #[derive(Debug)] pub struct GcmAes256; impl EncodeMessage for GcmAes256 { fn encode_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let nonce_sequence = NonceSequence::new().change_context(errors::CryptoError::EncodingFailed)?; let current_nonce = nonce_sequence.current(); let key = UnboundKey::new(&aead::AES_256_GCM, secret) .change_context(errors::CryptoError::EncodingFailed)?; let mut key = SealingKey::new(key, nonce_sequence); let mut in_out = msg.to_vec(); key.seal_in_place_append_tag(aead::Aad::empty(), &mut in_out) .change_context(errors::CryptoError::EncodingFailed)?; in_out.splice(0..0, current_nonce); Ok(in_out) } } impl DecodeMessage for GcmAes256 { fn decode_message( &self, secret: &[u8], msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError> { let msg = msg.expose(); let key = UnboundKey::new(&aead::AES_256_GCM, secret) .change_context(errors::CryptoError::DecodingFailed)?; let nonce_sequence = NonceSequence::from_bytes( <[u8; aead::NONCE_LEN]>::try_from( msg.get(..aead::NONCE_LEN) .ok_or(errors::CryptoError::DecodingFailed) .attach_printable("Failed to read the nonce form the encrypted ciphertext")?, ) .change_context(errors::CryptoError::DecodingFailed)?, ); let mut key = OpeningKey::new(key, nonce_sequence); let mut binding = msg; let output = binding.as_mut_slice(); let result = key .open_within(aead::Aad::empty(), output, aead::NONCE_LEN..) .change_context(errors::CryptoError::DecodingFailed)?; Ok(result.to_vec()) } } /// Represents the ED25519 signature verification algorithm #[derive(Debug)] pub struct Ed25519; impl Ed25519 { /// ED25519 algorithm constants const ED25519_PUBLIC_KEY_LEN: usize = 32; const ED25519_SIGNATURE_LEN: usize = 64; /// Validates ED25519 inputs (public key and signature lengths) fn validate_inputs( public_key: &[u8], signature: &[u8], ) -> CustomResult<(), errors::CryptoError> { // Validate public key length if public_key.len() != Self::ED25519_PUBLIC_KEY_LEN { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 public key length: expected {} bytes, got {}", Self::ED25519_PUBLIC_KEY_LEN, public_key.len() )); } // Validate signature length if signature.len() != Self::ED25519_SIGNATURE_LEN { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 signature length: expected {} bytes, got {}", Self::ED25519_SIGNATURE_LEN, signature.len() )); } Ok(()) } } impl VerifySignature for Ed25519 { fn verify_signature( &self, public_key: &[u8], signature: &[u8], // ED25519 signature bytes (must be 64 bytes) msg: &[u8], // Message that was signed ) -> CustomResult<bool, errors::CryptoError> { // Validate inputs first Self::validate_inputs(public_key, signature)?; // Create unparsed public key let ring_public_key = ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key); // Perform verification match ring_public_key.verify(msg, signature) { Ok(()) => Ok(true), Err(_err) => { #[cfg(feature = "logs")] logger::error!("ED25519 signature verification failed: {:?}", _err); Err(errors::CryptoError::SignatureVerificationFailed) .attach_printable("ED25519 signature verification failed") } } } } impl SignMessage for Ed25519 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { if secret.len() != 32 { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 private key length: expected 32 bytes, got {}", secret.len() )); } let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(secret) .change_context(errors::CryptoError::MessageSigningFailed) .attach_printable("Failed to create ED25519 key pair from seed")?; let signature = key_pair.sign(msg); Ok(signature.as_ref().to_vec()) } } /// Secure Hash Algorithm 512 #[derive(Debug)] pub struct Sha512; /// Secure Hash Algorithm 256 #[derive(Debug)] pub struct Sha256; /// Trait for generating a digest for SHA pub trait GenerateDigest { /// takes a message and creates a digest for it fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError>; } impl GenerateDigest for Sha512 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = ring::digest::digest(&ring::digest::SHA512, message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Sha512 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let msg_str = std::str::from_utf8(msg) .change_context(errors::CryptoError::EncodingFailed)? .to_owned(); let hashed_digest = hex::encode( Self.generate_digest(msg_str.as_bytes()) .change_context(errors::CryptoError::SignatureVerificationFailed)?, ); let hashed_digest_into_bytes = hashed_digest.into_bytes(); Ok(hashed_digest_into_bytes == signature) } } /// MD5 hash function #[derive(Debug)] pub struct Md5; impl GenerateDigest for Md5 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = md5::compute(message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Md5 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let hashed_digest = Self .generate_digest(msg) .change_context(errors::CryptoError::SignatureVerificationFailed)?; Ok(hashed_digest == signature) } } impl GenerateDigest for Sha256 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = ring::digest::digest(&ring::digest::SHA256, message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Sha256 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let hashed_digest = Self .generate_digest(msg) .change_context(errors::CryptoError::SignatureVerificationFailed)?; let hashed_digest_into_bytes = hashed_digest.as_slice(); Ok(hashed_digest_into_bytes == signature) } } /// Secure Hash Algorithm 256 with RSA public-key cryptosystem #[derive(Debug)] pub struct RsaSha256; impl VerifySignature for RsaSha256 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { // create verifying key let decoded_public_key = BASE64_ENGINE .decode(secret) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("base64 decoding failed")?; let string_public_key = String::from_utf8(decoded_public_key) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("utf8 to string parsing failed")?; let rsa_public_key = rsa::RsaPublicKey::from_public_key_pem(&string_public_key) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("rsa public key transformation failed")?; let verifying_key = rsa::pkcs1v15::VerifyingKey::<rsa::sha2::Sha256>::new(rsa_public_key); // transfrom the signature let decoded_signature = BASE64_ENGINE .decode(signature) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("base64 decoding failed")?; let rsa_signature = rsa::pkcs1v15::Signature::try_from(&decoded_signature[..]) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("rsa signature transformation failed")?; // signature verification verifying_key .verify(msg, &rsa_signature) .map(|_| true) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("signature verification step failed") } } /// TripleDesEde3 hash function #[derive(Debug)] #[cfg(feature = "crypto_openssl")] pub struct TripleDesEde3CBC { padding: common_enums::CryptoPadding, iv: Vec<u8>, } #[cfg(feature = "crypto_openssl")] impl TripleDesEde3CBC { const TRIPLE_DES_KEY_LENGTH: usize = 24; /// Initialization Vector (IV) length for TripleDesEde3 pub const TRIPLE_DES_IV_LENGTH: usize = 8; /// Constructor function to be used by the encryptor and decryptor to generate the data type pub fn new( padding: Option<common_enums::CryptoPadding>, iv: Vec<u8>, ) -> Result<Self, errors::CryptoError> { if iv.len() != Self::TRIPLE_DES_IV_LENGTH { Err(errors::CryptoError::InvalidIvLength)? }; let padding = padding.unwrap_or(common_enums::CryptoPadding::PKCS7); Ok(Self { iv, padding }) } } #[cfg(feature = "crypto_openssl")] impl EncodeMessage for TripleDesEde3CBC { fn encode_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { if secret.len() != Self::TRIPLE_DES_KEY_LENGTH { Err(errors::CryptoError::InvalidKeyLength)? } let mut buffer = msg.to_vec(); if let common_enums::CryptoPadding::ZeroPadding = self.padding { let pad_len = Self::TRIPLE_DES_IV_LENGTH - (buffer.len() % Self::TRIPLE_DES_IV_LENGTH); if pad_len != Self::TRIPLE_DES_IV_LENGTH { buffer.extend(vec![0u8; pad_len]); } }; let cipher = openssl::symm::Cipher::des_ede3_cbc(); openssl::symm::encrypt(cipher, secret, Some(&self.iv), &buffer) .change_context(errors::CryptoError::EncodingFailed) } } /// Generate a random string using a cryptographically secure pseudo-random number generator /// (CSPRNG). Typically used for generating (readable) keys and passwords. #[inline] pub fn generate_cryptographically_secure_random_string(length: usize) -> String { use rand::distributions::DistString; rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length) } /// Generate an array of random bytes using a cryptographically secure pseudo-random number /// generator (CSPRNG). Typically used for generating keys. #[inline] pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] { use rand::RngCore; let mut bytes = [0; N]; rand::rngs::OsRng.fill_bytes(&mut bytes); bytes } /// A wrapper type to store the encrypted data for sensitive pii domain data types #[derive(Debug, Clone)] pub struct Encryptable<T: Clone> { inner: T, encrypted: Secret<Vec<u8>, EncryptionStrategy>, } impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { /// constructor function to be used by the encryptor and decryptor to generate the data type pub fn new( masked_data: Secret<T, S>, encrypted_data: Secret<Vec<u8>, EncryptionStrategy>, ) -> Self { Self { inner: masked_data, encrypted: encrypted_data, } } } impl<T: Clone> Encryptable<T> { /// Get the inner data while consuming self #[inline] pub fn into_inner(self) -> T { self.inner } /// Get the reference to inner value #[inline] pub fn get_inner(&self) -> &T { &self.inner } /// Get the inner encrypted data while consuming self #[inline] pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.encrypted } /// Deserialize inner value and return new Encryptable object pub fn deserialize_inner_value<U, F>( self, f: F, ) -> CustomResult<Encryptable<U>, errors::ParsingError> where F: FnOnce(T) -> CustomResult<U, errors::ParsingError>, U: Clone, { let inner = self.inner; let encrypted = self.encrypted; let inner = f(inner)?; Ok(Encryptable { inner, encrypted }) } /// consume self and modify the inner value pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> { let encrypted_data = self.encrypted; let masked_data = f(self.inner); Encryptable { inner: masked_data, encrypted: encrypted_data, } } } impl<T: Clone> Deref for Encryptable<Secret<T>> { type Target = Secret<T>; fn deref(&self) -> &Self::Target { &self.inner } } impl<T: Clone> masking::Serialize for Encryptable<T> where T: masking::Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.inner.serialize(serializer) } } impl<T: Clone> PartialEq for Encryptable<T> where T: PartialEq, { fn eq(&self, other: &Self) -> bool { self.inner.eq(&other.inner) } } /// Type alias for `Option<Encryptable<Secret<String>>>` pub type OptionalEncryptableSecretString = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `name` field pub type OptionalEncryptableName = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `email` field pub type OptionalEncryptableEmail = Option<Encryptable<Secret<String, pii::EmailStrategy>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `phone` field pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<serde_json::Value>>>` pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>; /// Type alias for `Option<Secret<serde_json::Value>>` pub type OptionalSecretValue = Option<Secret<serde_json::Value>>; /// Type alias for `Encryptable<Secret<String>>` used for `name` field pub type EncryptableName = Encryptable<Secret<String>>; /// Type alias for `Encryptable<Secret<String>>` used for `email` field pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>; /// Extract RSA public key components (n, e) from a private key PEM for JWKS /// Returns base64url-encoded modulus and exponent pub fn extract_rsa_public_key_components( private_key_pem: &Secret<String>, ) -> CustomResult<(String, String), errors::CryptoError> { let pem_str = private_key_pem.peek(); let parsed_pem = pem::parse(pem_str).change_context(errors::CryptoError::EncodingFailed)?; let private_key = match parsed_pem.tag() { "PRIVATE KEY" => rsa::RsaPrivateKey::from_pkcs8_der(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength), "RSA PRIVATE KEY" => rsa::RsaPrivateKey::from_pkcs1_der(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength), tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'" )), } .attach_printable("Failed to extract RSA public key components from private key")?; let public_key = private_key.to_public_key(); let n_bytes = public_key.n().to_bytes_be(); let e_bytes = public_key.e().to_bytes_be(); let n_b64 = BASE64_ENGINE_URL_SAFE_NO_PAD.encode(n_bytes); let e_b64 = BASE64_ENGINE_URL_SAFE_NO_PAD.encode(e_bytes); Ok((n_b64, e_b64)) } /// Represents the RSA-PSS-SHA256 signing algorithm #[derive(Debug)] pub struct RsaPssSha256; impl SignMessage for RsaPssSha256 { fn sign_message( &self, private_key_pem_bytes: &[u8], msg_to_sign: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let parsed_pem = pem::parse(private_key_pem_bytes) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to parse PEM string")?; let key_pair = match parsed_pem.tag() { "PRIVATE KEY" => RsaKeyPair::from_pkcs8(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength) .attach_printable("Failed to parse PKCS#8 DER with ring"), "RSA PRIVATE KEY" => RsaKeyPair::from_der(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength) .attach_printable("Failed to parse PKCS#1 DER (using from_der) with ring"), tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'", )), }?; let rng = ring_rand::SystemRandom::new(); let signature_len = key_pair.public().modulus_len(); let mut signature_bytes = vec![0; signature_len]; key_pair .sign(&RSA_PSS_SHA256, &rng, msg_to_sign, &mut signature_bytes) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to sign data with ring")?; Ok(signature_bytes) } } #[cfg(test)] mod crypto_tests { use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature}; use crate::crypto::GenerateDigest; #[test] fn test_hmac_sha256_sign_message() { let message = r#"{"type":"payment_intent"}"#.as_bytes(); let secret = "hmac_secret_1234".as_bytes(); let right_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e") .expect("Right signature decoding"); let signature = super::HmacSha256 .sign_message(secret, message) .expect("Signature"); assert_eq!(signature, right_signature); } #[test] fn test_hmac_sha256_verify_signature() { let right_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e") .expect("Right signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "hmac_secret_1234".as_bytes(); let data = r#"{"type":"payment_intent"}"#.as_bytes(); let right_verified = super::HmacSha256 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::HmacSha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_sha256_verify_signature() { let right_signature = hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddba") .expect("Right signature decoding"); let wrong_signature = hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddbb") .expect("Wrong signature decoding"); let secret = "".as_bytes(); let data = r#"AJHFH9349JASFJHADJ9834115USD2020-11-13.13:22:34711000000021406655APPROVED12345product_id"#.as_bytes(); let right_verified = super::Sha256 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::Sha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_hmac_sha512_sign_message() { let message = r#"{"type":"payment_intent"}"#.as_bytes(); let secret = "hmac_secret_1234".as_bytes(); let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f") .expect("signature decoding"); let signature = super::HmacSha512 .sign_message(secret, message) .expect("Signature"); assert_eq!(signature, right_signature); } #[test] fn test_hmac_sha512_verify_signature() { let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f") .expect("signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "hmac_secret_1234".as_bytes(); let data = r#"{"type":"payment_intent"}"#.as_bytes(); let right_verified = super::HmacSha512 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::HmacSha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_gcm_aes_256_encode_message() { let message = r#"{"type":"PAYMENT"}"#.as_bytes(); let secret = hex::decode("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") .expect("Secret decoding"); let algorithm = super::GcmAes256; let encoded_message = algorithm .encode_message(&secret, message) .expect("Encoded message and tag"); assert_eq!( algorithm .decode_message(&secret, encoded_message.into()) .expect("Decode Failed"), message ); } #[test] fn test_gcm_aes_256_decode_message() { // Inputs taken from AES GCM test vectors provided by NIST // https://github.com/briansmith/ring/blob/95948b3977013aed16db92ae32e6b8384496a740/tests/aead_aes_256_gcm_tests.txt#L447-L452 let right_secret = hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308") .expect("Secret decoding"); let wrong_secret = hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308309") .expect("Secret decoding"); let message = // The three parts of the message are the nonce, ciphertext and tag from the test vector hex::decode( "cafebabefacedbaddecaf888\ 522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad\ b094dac5d93471bdec1a502270e3cc6c" ).expect("Message decoding"); let algorithm = super::GcmAes256; let decoded = algorithm .decode_message(&right_secret, message.clone().into()) .expect("Decoded message"); assert_eq!( decoded, hex::decode("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255") .expect("Decoded plaintext message") ); let err_decoded = algorithm.decode_message(&wrong_secret, message.into()); assert!(err_decoded.is_err()); } #[test] fn test_md5_digest() { let message = "abcdefghijklmnopqrstuvwxyz".as_bytes(); assert_eq!( format!(
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/fp_utils.rs
crates/common_utils/src/fp_utils.rs
//! Functional programming utilities /// The Applicative trait provides a pure behavior, /// which can be used to create values of type f a from values of type a. pub trait Applicative<R> { /// The Associative type acts as a (f a) wrapper for Self. type WrappedSelf<T>; /// Applicative::pure(_) is abstraction with lifts any arbitrary type to underlying higher /// order type fn pure(v: R) -> Self::WrappedSelf<R>; } impl<R> Applicative<R> for Option<R> { type WrappedSelf<T> = Option<T>; fn pure(v: R) -> Self::WrappedSelf<R> { Some(v) } } impl<R, E> Applicative<R> for Result<R, E> { type WrappedSelf<T> = Result<T, E>; fn pure(v: R) -> Self::WrappedSelf<R> { Ok(v) } } /// This function wraps the evaluated result of `f` into current context, /// based on the condition provided into the `predicate` pub fn when<W: Applicative<(), WrappedSelf<()> = W>, F>(predicate: bool, f: F) -> W where F: FnOnce() -> W, { if predicate { f() } else { W::pure(()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/signals.rs
crates/common_utils/src/signals.rs
//! Provide Interface for worker services to handle signals #[cfg(not(target_os = "windows"))] use futures::StreamExt; #[cfg(not(target_os = "windows"))] use router_env::logger; use tokio::sync::mpsc; /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received #[cfg(not(target_os = "windows"))] pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) { if let Some(signal) = sig.next().await { logger::info!( "Received signal: {:?}", signal_hook::low_level::signal_name(signal) ); match signal { signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.try_send(()) { Ok(_) => { logger::info!("Request for force shutdown received") } Err(_) => { logger::error!( "The receiver is closed, a termination call might already be sent" ) } }, _ => {} } } } /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received #[cfg(target_os = "windows")] pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {} /// This function is used to generate a list of signals that the signal_handler should listen for #[cfg(not(target_os = "windows"))] pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> { signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT]) } /// This function is used to generate a list of signals that the signal_handler should listen for #[cfg(target_os = "windows")] pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> { Ok(DummySignal) } /// Dummy Signal Handler for windows #[cfg(target_os = "windows")] #[derive(Debug, Clone)] pub struct DummySignal; #[cfg(target_os = "windows")] impl DummySignal { /// Dummy handler for signals in windows (empty) pub fn handle(&self) -> Self { self.clone() } /// Hollow implementation, for windows compatibility pub fn close(self) {} }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/hashing.rs
crates/common_utils/src/hashing.rs
use masking::{PeekInterface, Secret, Strategy}; use serde::{Deserialize, Serialize, Serializer}; #[derive(Clone, PartialEq, Debug, Deserialize)] /// Represents a hashed string using blake3's hashing strategy. pub struct HashedString<T: Strategy<String>>(Secret<String, T>); impl<T: Strategy<String>> Serialize for HashedString<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let hashed_value = blake3::hash(self.0.peek().as_bytes()).to_hex(); hashed_value.serialize(serializer) } } impl<T: Strategy<String>> From<Secret<String, T>> for HashedString<T> { fn from(value: Secret<String, T>) -> Self { Self(value) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/tokenization.rs
crates/common_utils/src/tokenization.rs
//! Module for tokenization-related functionality //! //! This module provides types and functions for handling tokenized payment data, //! including response structures and token generation utilities. use crate::consts::TOKEN_LENGTH; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] /// Generates a new token string /// /// # Returns /// A randomly generated token string of length `TOKEN_LENGTH` pub fn generate_token() -> String { use nanoid::nanoid; nanoid!(TOKEN_LENGTH) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/metrics/utils.rs
crates/common_utils/src/metrics/utils.rs
//! metric utility functions use std::time; use router_env::opentelemetry; /// Record the time taken by the future to execute #[inline] pub async fn time_future<F, R>(future: F) -> (R, time::Duration) where F: futures::Future<Output = R>, { let start = time::Instant::now(); let result = future.await; let time_spent = start.elapsed(); (result, time_spent) } /// Record the time taken (in seconds) by the operation for the given context #[inline] pub async fn record_operation_time<F, R>( future: F, metric: &opentelemetry::metrics::Histogram<f64>, key_value: &[opentelemetry::KeyValue], ) -> R where F: futures::Future<Output = R>, { let (result, time) = time_future(future).await; metric.record(time.as_secs_f64(), key_value); result }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/tenant.rs
crates/common_utils/src/id_type/tenant.rs
use crate::{ consts::{DEFAULT_GLOBAL_TENANT_ID, DEFAULT_TENANT}, errors::{CustomResult, ValidationError}, }; crate::id_type!( TenantId, "A type for tenant_id that can be used for unique identifier for a tenant" ); crate::impl_id_type_methods!(TenantId, "tenant_id"); // This is to display the `TenantId` as TenantId(abcd) crate::impl_debug_id_type!(TenantId); crate::impl_try_from_cow_str_id_type!(TenantId, "tenant_id"); crate::impl_serializable_secret_id_type!(TenantId); crate::impl_queryable_id_type!(TenantId); crate::impl_to_sql_from_sql_id_type!(TenantId); impl TenantId { /// Get the default global tenant ID pub fn get_default_global_tenant_id() -> Self { Self(super::LengthId::new_unchecked( super::AlphaNumericId::new_unchecked(DEFAULT_GLOBAL_TENANT_ID.to_string()), )) } /// Get the default tenant ID pub fn get_default_tenant_id() -> Self { Self(super::LengthId::new_unchecked( super::AlphaNumericId::new_unchecked(DEFAULT_TENANT.to_string()), )) } /// Get tenant id from String pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(tenant_id)) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/refunds.rs
crates/common_utils/src/id_type/refunds.rs
crate::id_type!(RefundReferenceId, "A type for refund_reference_id"); crate::impl_id_type_methods!(RefundReferenceId, "refund_reference_id"); // This is to display the `RefundReferenceId` as RefundReferenceId(abcd) crate::impl_debug_id_type!(RefundReferenceId); crate::impl_try_from_cow_str_id_type!(RefundReferenceId, "refund_reference_id"); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(RefundReferenceId); crate::impl_to_sql_from_sql_id_type!(RefundReferenceId);
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/routing.rs
crates/common_utils/src/id_type/routing.rs
crate::id_type!( RoutingId, " A type for routing_id that can be used for routing ids" ); crate::impl_id_type_methods!(RoutingId, "routing_id"); // This is to display the `RoutingId` as RoutingId(abcd) crate::impl_debug_id_type!(RoutingId); crate::impl_try_from_cow_str_id_type!(RoutingId, "routing_id"); crate::impl_generate_id_id_type!(RoutingId, "routing"); crate::impl_serializable_secret_id_type!(RoutingId); crate::impl_queryable_id_type!(RoutingId); crate::impl_to_sql_from_sql_id_type!(RoutingId); impl crate::events::ApiEventMetric for RoutingId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Routing) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/profile_acquirer.rs
crates/common_utils/src/id_type/profile_acquirer.rs
use std::str::FromStr; crate::id_type!( ProfileAcquirerId, "A type for profile_acquirer_id that can be used for profile acquirer ids" ); crate::impl_id_type_methods!(ProfileAcquirerId, "profile_acquirer_id"); // This is to display the `ProfileAcquirerId` as ProfileAcquirerId(abcd) crate::impl_debug_id_type!(ProfileAcquirerId); crate::impl_try_from_cow_str_id_type!(ProfileAcquirerId, "profile_acquirer_id"); crate::impl_generate_id_id_type!(ProfileAcquirerId, "pro_acq"); crate::impl_serializable_secret_id_type!(ProfileAcquirerId); crate::impl_queryable_id_type!(ProfileAcquirerId); crate::impl_to_sql_from_sql_id_type!(ProfileAcquirerId); impl Ord for ProfileAcquirerId { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0 .0 .0.cmp(&other.0 .0 .0) } } impl PartialOrd for ProfileAcquirerId { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl crate::events::ApiEventMetric for ProfileAcquirerId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ProfileAcquirer { profile_acquirer_id: self.clone(), }) } } impl FromStr for ProfileAcquirerId { type Err = error_stack::Report<crate::errors::ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } } // This is implemented so that we can use profile acquirer id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<ProfileAcquirerId> for router_env::opentelemetry::Value { fn from(val: ProfileAcquirerId) -> Self { Self::from(val.0 .0 .0) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/organization.rs
crates/common_utils/src/id_type/organization.rs
use crate::errors::{CustomResult, ValidationError}; crate::id_type!( OrganizationId, "A type for organization_id that can be used for organization ids" ); crate::impl_id_type_methods!(OrganizationId, "organization_id"); // This is to display the `OrganizationId` as OrganizationId(abcd) crate::impl_debug_id_type!(OrganizationId); crate::impl_default_id_type!(OrganizationId, "org"); crate::impl_try_from_cow_str_id_type!(OrganizationId, "organization_id"); crate::impl_generate_id_id_type!(OrganizationId, "org"); crate::impl_serializable_secret_id_type!(OrganizationId); crate::impl_queryable_id_type!(OrganizationId); crate::impl_to_sql_from_sql_id_type!(OrganizationId); impl OrganizationId { /// Get an organization id from String pub fn try_from_string(org_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(org_id)) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/client_secret.rs
crates/common_utils/src/id_type/client_secret.rs
crate::id_type!( ClientSecretId, "A type for key_id that can be used for Ephemeral key IDs" ); crate::impl_id_type_methods!(ClientSecretId, "key_id"); // This is to display the `ClientSecretId` as ClientSecretId(abcd) crate::impl_debug_id_type!(ClientSecretId); crate::impl_try_from_cow_str_id_type!(ClientSecretId, "key_id"); crate::impl_generate_id_id_type!(ClientSecretId, "csi"); crate::impl_serializable_secret_id_type!(ClientSecretId); crate::impl_queryable_id_type!(ClientSecretId); crate::impl_to_sql_from_sql_id_type!(ClientSecretId); #[cfg(feature = "v2")] impl crate::events::ApiEventMetric for ClientSecretId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ClientSecret { key_id: self.clone(), }) } } crate::impl_default_id_type!(ClientSecretId, "key"); impl ClientSecretId { /// Generate a key for redis pub fn generate_redis_key(&self) -> String { format!("cs_{}", self.get_string_repr()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/subscription.rs
crates/common_utils/src/id_type/subscription.rs
crate::id_type!( SubscriptionId, " A type for subscription_id that can be used for subscription ids" ); crate::impl_id_type_methods!(SubscriptionId, "subscription_id"); // This is to display the `SubscriptionId` as SubscriptionId(subs) crate::impl_debug_id_type!(SubscriptionId); crate::impl_try_from_cow_str_id_type!(SubscriptionId, "subscription_id"); crate::impl_generate_id_id_type!(SubscriptionId, "sub"); crate::impl_serializable_secret_id_type!(SubscriptionId); crate::impl_queryable_id_type!(SubscriptionId); crate::impl_to_sql_from_sql_id_type!(SubscriptionId); impl crate::events::ApiEventMetric for SubscriptionId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Subscription) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/invoice.rs
crates/common_utils/src/id_type/invoice.rs
crate::id_type!( InvoiceId, " A type for invoice_id that can be used for invoice ids" ); crate::impl_id_type_methods!(InvoiceId, "invoice_id"); // This is to display the `InvoiceId` as InvoiceId(subs) crate::impl_debug_id_type!(InvoiceId); crate::impl_try_from_cow_str_id_type!(InvoiceId, "invoice_id"); crate::impl_generate_id_id_type!(InvoiceId, "invoice"); crate::impl_serializable_secret_id_type!(InvoiceId); crate::impl_queryable_id_type!(InvoiceId); crate::impl_to_sql_from_sql_id_type!(InvoiceId); impl crate::events::ApiEventMetric for InvoiceId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Invoice) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/relay.rs
crates/common_utils/src/id_type/relay.rs
use std::str::FromStr; crate::id_type!( RelayId, "A type for relay_id that can be used for relay ids" ); crate::impl_id_type_methods!(RelayId, "relay_id"); crate::impl_try_from_cow_str_id_type!(RelayId, "relay_id"); crate::impl_generate_id_id_type!(RelayId, "relay"); crate::impl_serializable_secret_id_type!(RelayId); crate::impl_queryable_id_type!(RelayId); crate::impl_to_sql_from_sql_id_type!(RelayId); crate::impl_debug_id_type!(RelayId); impl FromStr for RelayId { type Err = error_stack::Report<crate::errors::ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/api_key.rs
crates/common_utils/src/id_type/api_key.rs
crate::id_type!( ApiKeyId, "A type for key_id that can be used for API key IDs" ); crate::impl_id_type_methods!(ApiKeyId, "key_id"); // This is to display the `ApiKeyId` as ApiKeyId(abcd) crate::impl_debug_id_type!(ApiKeyId); crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id"); crate::impl_serializable_secret_id_type!(ApiKeyId); crate::impl_queryable_id_type!(ApiKeyId); crate::impl_to_sql_from_sql_id_type!(ApiKeyId); impl ApiKeyId { /// Generate Api Key Id from prefix pub fn generate_key_id(prefix: &'static str) -> Self { Self(crate::generate_ref_id_with_default_length(prefix)) } } impl crate::events::ApiEventMetric for ApiKeyId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ApiKey { key_id: self.clone(), }) } } impl crate::events::ApiEventMetric for (super::MerchantId, ApiKeyId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ApiKey { key_id: self.1.clone(), }) } } impl crate::events::ApiEventMetric for (&super::MerchantId, &ApiKeyId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ApiKey { key_id: self.1.clone(), }) } } crate::impl_default_id_type!(ApiKeyId, "key");
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/merchant_connector_account.rs
crates/common_utils/src/id_type/merchant_connector_account.rs
use std::str::FromStr; use crate::errors::{CustomResult, ValidationError}; crate::id_type!( MerchantConnectorAccountId, "A type for merchant_connector_id that can be used for merchant_connector_account ids" ); crate::impl_id_type_methods!(MerchantConnectorAccountId, "merchant_connector_id"); // This is to display the `MerchantConnectorAccountId` as MerchantConnectorAccountId(abcd) crate::impl_debug_id_type!(MerchantConnectorAccountId); crate::impl_generate_id_id_type!(MerchantConnectorAccountId, "mca"); crate::impl_try_from_cow_str_id_type!(MerchantConnectorAccountId, "merchant_connector_id"); crate::impl_serializable_secret_id_type!(MerchantConnectorAccountId); crate::impl_queryable_id_type!(MerchantConnectorAccountId); crate::impl_to_sql_from_sql_id_type!(MerchantConnectorAccountId); impl MerchantConnectorAccountId { /// Get a merchant connector account id from String pub fn wrap(merchant_connector_account_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(merchant_connector_account_id)) } } impl FromStr for MerchantConnectorAccountId { type Err = std::fmt::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::try_from(std::borrow::Cow::Owned(s.to_string())).map_err(|_| std::fmt::Error) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/payment.rs
crates/common_utils/src/id_type/payment.rs
use crate::{ errors::{CustomResult, ValidationError}, generate_id_with_default_len, id_type::{AlphaNumericId, LengthId}, }; crate::id_type!( PaymentId, "A type for payment_id that can be used for payment ids" ); crate::impl_id_type_methods!(PaymentId, "payment_id"); // This is to display the `PaymentId` as PaymentId(abcd) crate::impl_debug_id_type!(PaymentId); crate::impl_default_id_type!(PaymentId, "pay"); crate::impl_try_from_cow_str_id_type!(PaymentId, "payment_id"); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(PaymentId); crate::impl_to_sql_from_sql_id_type!(PaymentId); impl PaymentId { /// Get the hash key to be stored in redis pub fn get_hash_key_for_kv_store(&self) -> String { format!("pi_{}", self.0 .0 .0) } // This function should be removed once we have a better way to handle mandatory payment id in other flows /// Get payment id in the format of irrelevant_payment_id_in_{flow} pub fn get_irrelevant_id(flow: &str) -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked(format!("irrelevant_payment_id_in_{flow}")); let id = LengthId::new_unchecked(alphanumeric_id); Self(id) } /// Get the attempt id for the payment id based on the attempt count pub fn get_attempt_id(&self, attempt_count: i16) -> String { format!("{}_{attempt_count}", self.get_string_repr()) } /// Generate a client id for the payment id pub fn generate_client_secret(&self) -> String { generate_id_with_default_len(&format!("{}_secret", self.get_string_repr())) } /// Generate a key for pm_auth pub fn get_pm_auth_key(&self) -> String { format!("pm_auth_{}", self.get_string_repr()) } /// Get external authentication request poll id pub fn get_external_authentication_request_poll_id(&self) -> String { format!("external_authentication_{}", self.get_string_repr()) } /// Generate a test payment id with prefix test_ pub fn generate_test_payment_id_for_sample_data() -> Self { let id = generate_id_with_default_len("test"); let alphanumeric_id = AlphaNumericId::new_unchecked(id); let id = LengthId::new_unchecked(alphanumeric_id); Self(id) } /// Wrap a string inside PaymentId pub fn wrap(payment_id_string: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(payment_id_string)) } } crate::id_type!(PaymentReferenceId, "A type for payment_reference_id"); crate::impl_id_type_methods!(PaymentReferenceId, "payment_reference_id"); // This is to display the `PaymentReferenceId` as PaymentReferenceId(abcd) crate::impl_debug_id_type!(PaymentReferenceId); crate::impl_try_from_cow_str_id_type!(PaymentReferenceId, "payment_reference_id"); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(PaymentReferenceId); crate::impl_to_sql_from_sql_id_type!(PaymentReferenceId); // This is implemented so that we can use payment id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<PaymentId> for router_env::opentelemetry::Value { fn from(val: PaymentId) -> Self { Self::from(val.0 .0 .0) } } impl std::str::FromStr for PaymentReferenceId { type Err = error_stack::Report<ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/payout.rs
crates/common_utils/src/id_type/payout.rs
crate::id_type!( PayoutId, "A domain type for payout_id that can be used for payout ids" ); crate::impl_id_type_methods!(PayoutId, "payout_id"); crate::impl_debug_id_type!(PayoutId); crate::impl_try_from_cow_str_id_type!(PayoutId, "payout_id"); crate::impl_generate_id_id_type!(PayoutId, "payout"); crate::impl_queryable_id_type!(PayoutId); crate::impl_to_sql_from_sql_id_type!(PayoutId);
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/global_id.rs
crates/common_utils/src/id_type/global_id.rs
pub(super) mod customer; pub(super) mod payment; pub(super) mod payment_methods; pub(super) mod refunds; pub(super) mod token; use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types}; use error_stack::ResultExt; use thiserror::Error; use crate::{ consts::{CELL_IDENTIFIER_LENGTH, MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH}, errors, generate_time_ordered_id, id_type::{AlphaNumericId, AlphaNumericIdError, LengthId, LengthIdError}, }; #[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)] /// A global id that can be used to identify any entity /// This id will have information about the entity and cell in a distributed system architecture pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>); #[derive(Clone, Copy)] /// Entities that can be identified by a global id pub(crate) enum GlobalEntity { Customer, Payment, Attempt, AttemptGroup, PaymentMethod, Refund, PaymentMethodSession, Token, } impl GlobalEntity { fn prefix(self) -> &'static str { match self { Self::Customer => "cus", Self::Payment => "pay", Self::PaymentMethod => "pm", Self::Attempt => "att", Self::AttemptGroup => "atg", Self::Refund => "ref", Self::PaymentMethodSession => "pms", Self::Token => "tok", } } } /// Cell identifier for an instance / deployment of application #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct CellId(LengthId<CELL_IDENTIFIER_LENGTH, CELL_IDENTIFIER_LENGTH>); #[derive(Debug, Error, PartialEq, Eq)] pub enum CellIdError { #[error("cell id error: {0}")] InvalidCellLength(LengthIdError), #[error("{0}")] InvalidCellIdFormat(AlphaNumericIdError), } impl From<LengthIdError> for CellIdError { fn from(error: LengthIdError) -> Self { Self::InvalidCellLength(error) } } impl From<AlphaNumericIdError> for CellIdError { fn from(error: AlphaNumericIdError) -> Self { Self::InvalidCellIdFormat(error) } } impl CellId { /// Create a new cell id from a string fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> { let trimmed_input_string = cell_id_string.as_ref().trim().to_string(); let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?; let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?; Ok(Self(length_id)) } /// Create a new cell id from a string pub fn from_string( input_string: impl AsRef<str>, ) -> error_stack::Result<Self, errors::ValidationError> { Self::from_str(input_string).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "cell_id", }, ) } /// Get the string representation of the cell id fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } impl<'de> serde::Deserialize<'de> for CellId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom) } } /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum GlobalIdError { /// The format for the global id is invalid #[error("The id format is invalid, expected format is {{cell_id:5}}_{{entity_prefix:3}}_{{uuid:32}}_{{random:24}}")] InvalidIdFormat, /// LengthIdError and AlphanumericIdError #[error("{0}")] LengthIdError(#[from] LengthIdError), /// CellIdError because of invalid cell id format #[error("{0}")] CellIdError(#[from] CellIdError), } impl GlobalId { /// Create a new global id from entity and cell information /// The entity prefix is used to identify the entity, `cus` for customers, `pay`` for payments etc. pub fn generate(cell_id: &CellId, entity: GlobalEntity) -> Self { let prefix = format!("{}_{}", cell_id.get_string_repr(), entity.prefix()); let id = generate_time_ordered_id(&prefix); let alphanumeric_id = AlphaNumericId::new_unchecked(id); Self(LengthId::new_unchecked(alphanumeric_id)) } pub(crate) fn from_string( input_string: std::borrow::Cow<'static, str>, ) -> Result<Self, GlobalIdError> { let length_id = LengthId::from(input_string)?; let input_string = &length_id.0 .0; let (cell_id, _remaining) = input_string .split_once("_") .ok_or(GlobalIdError::InvalidIdFormat)?; CellId::from_str(cell_id)?; Ok(Self(length_id)) } pub(crate) fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } impl<DB> ToSql<sql_types::Text, DB> for GlobalId where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0 .0 .0.to_sql(out) } } impl<DB> FromSql<sql_types::Text, DB> for GlobalId where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let string_val = String::from_sql(value)?; let alphanumeric_id = AlphaNumericId::from(string_val.into())?; let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?; Ok(Self(length_id)) } } /// Deserialize the global id from string /// The format should match {cell_id:5}_{entity_prefix:3}_{time_ordered_id:32}_{.*:24} impl<'de> serde::Deserialize<'de> for GlobalId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from_string(deserialized_string.into()).map_err(serde::de::Error::custom) } } #[cfg(test)] mod global_id_tests { use super::*; #[test] fn test_cell_id_from_str() { let cell_id_string = "12345"; let cell_id = CellId::from_str(cell_id_string).unwrap(); assert_eq!(cell_id.get_string_repr(), cell_id_string); } #[test] fn test_global_id_generate() { let cell_id_string = "12345"; let entity = GlobalEntity::Customer; let cell_id = CellId::from_str(cell_id_string).unwrap(); let global_id = GlobalId::generate(&cell_id, entity); // Generate a regex for globalid // Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890 let regex = regex::Regex::new(r"[a-z0-9]{5}_cus_[a-z0-9]{32}").unwrap(); assert!(regex.is_match(&global_id.0 .0 .0)); } #[test] fn test_global_id_from_string() { let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890"; let global_id = GlobalId::from_string(input_string.into()).unwrap(); assert_eq!(global_id.0 .0 .0, input_string); } #[test] fn test_global_id_deser() { let input_string_for_serde_json_conversion = r#""12345_cus_abcdefghijklmnopqrstuvwxyz1234567890""#; let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890"; let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion).unwrap(); assert_eq!(global_id.0 .0 .0, input_string); } #[test] fn test_global_id_deser_error() { let input_string_for_serde_json_conversion = r#""123_45_cus_abcdefghijklmnopqrstuvwxyz1234567890""#; let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion); assert!(global_id.is_err()); let expected_error_message = format!( "cell id error: the minimum required length for this field is {CELL_IDENTIFIER_LENGTH}" ); let error_message = global_id.unwrap_err().to_string(); assert_eq!(error_message, expected_error_message); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/authentication.rs
crates/common_utils/src/id_type/authentication.rs
crate::id_type!( AuthenticationId, "A type for authentication_id that can be used for authentication IDs" ); crate::impl_id_type_methods!(AuthenticationId, "authentication_id"); // This is to display the `AuthenticationId` as AuthenticationId(abcd) crate::impl_debug_id_type!(AuthenticationId); crate::impl_try_from_cow_str_id_type!(AuthenticationId, "authentication_id"); crate::impl_serializable_secret_id_type!(AuthenticationId); crate::impl_queryable_id_type!(AuthenticationId); crate::impl_to_sql_from_sql_id_type!(AuthenticationId); impl AuthenticationId { /// Generate Authentication Id from prefix pub fn generate_authentication_id(prefix: &'static str) -> Self { Self(crate::generate_ref_id_with_default_length(prefix)) } /// Get external authentication request poll id pub fn get_external_authentication_request_poll_id(&self) -> String { format!("external_authentication_{}", self.get_string_repr()) } } impl crate::events::ApiEventMetric for AuthenticationId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Authentication { authentication_id: self.clone(), }) } } impl crate::events::ApiEventMetric for (super::MerchantId, AuthenticationId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Authentication { authentication_id: self.1.clone(), }) } } impl crate::events::ApiEventMetric for (&super::MerchantId, &AuthenticationId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Authentication { authentication_id: self.1.clone(), }) } } crate::impl_default_id_type!(AuthenticationId, "authentication");
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/customer.rs
crates/common_utils/src/id_type/customer.rs
crate::id_type!( CustomerId, "A type for customer_id that can be used for customer ids" ); crate::impl_id_type_methods!(CustomerId, "customer_id"); // This is to display the `CustomerId` as CustomerId(abcd) crate::impl_debug_id_type!(CustomerId); crate::impl_default_id_type!(CustomerId, "cus"); crate::impl_try_from_cow_str_id_type!(CustomerId, "customer_id"); crate::impl_generate_id_id_type!(CustomerId, "cus"); crate::impl_serializable_secret_id_type!(CustomerId); crate::impl_queryable_id_type!(CustomerId); crate::impl_to_sql_from_sql_id_type!(CustomerId); #[cfg(feature = "v1")] impl crate::events::ApiEventMetric for CustomerId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Customer { customer_id: self.clone(), }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/webhook_endpoint.rs
crates/common_utils/src/id_type/webhook_endpoint.rs
use crate::errors::{CustomResult, ValidationError}; crate::id_type!( WebhookEndpointId, "A type for webhook_endpoint_id that can be used for unique identifier for a webhook_endpoint" ); crate::impl_id_type_methods!(WebhookEndpointId, "webhook_endpoint_id"); crate::impl_generate_id_id_type!(WebhookEndpointId, "whe"); crate::impl_default_id_type!(WebhookEndpointId, "whe"); // This is to display the `WebhookEndpointId` as WebhookEndpointId(abcd) crate::impl_debug_id_type!(WebhookEndpointId); crate::impl_try_from_cow_str_id_type!(WebhookEndpointId, "webhook_endpoint_id"); crate::impl_serializable_secret_id_type!(WebhookEndpointId); crate::impl_queryable_id_type!(WebhookEndpointId); crate::impl_to_sql_from_sql_id_type!(WebhookEndpointId); impl WebhookEndpointId { /// Get webhook_endpoint id from String pub fn try_from_string(webhook_endpoint_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(webhook_endpoint_id)) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/merchant.rs
crates/common_utils/src/id_type/merchant.rs
//! Contains the id type for merchant account //! //! Ids for merchant account are derived from the merchant name //! If there are any special characters, they are removed use crate::{ date_time, errors::{CustomResult, ValidationError}, generate_id_with_default_len, id_type::{AlphaNumericId, LengthId}, new_type::MerchantName, types::keymanager, }; crate::id_type!( MerchantId, "A type for merchant_id that can be used for merchant ids" ); crate::impl_id_type_methods!(MerchantId, "merchant_id"); // This is to display the `MerchantId` as MerchantId(abcd) crate::impl_debug_id_type!(MerchantId); crate::impl_default_id_type!(MerchantId, "mer"); crate::impl_try_from_cow_str_id_type!(MerchantId, "merchant_id"); crate::impl_generate_id_id_type!(MerchantId, "mer"); crate::impl_serializable_secret_id_type!(MerchantId); crate::impl_queryable_id_type!(MerchantId); crate::impl_to_sql_from_sql_id_type!(MerchantId); // This is implemented so that we can use merchant id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<MerchantId> for router_env::opentelemetry::Value { fn from(val: MerchantId) -> Self { Self::from(val.0 .0 .0) } } impl MerchantId { /// Create a Merchant id from MerchantName pub fn from_merchant_name(merchant_name: MerchantName) -> Self { let merchant_name_string = merchant_name.into_inner(); let merchant_id_prefix = merchant_name_string.trim().to_lowercase().replace(' ', ""); let alphanumeric_id = AlphaNumericId::new_unchecked(generate_id_with_default_len(&merchant_id_prefix)); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id with the const value of `MERCHANT_ID_NOT_FOUND` pub fn get_merchant_id_not_found() -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked("MERCHANT_ID_NOT_FOUND".to_string()); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id for internal use only pub fn get_internal_user_merchant_id(merchant_id: &str) -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id.to_string()); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Create a new merchant_id from unix timestamp, of the format `merchant_{timestamp}` pub fn new_from_unix_timestamp() -> Self { let merchant_id = format!("merchant_{}", date_time::now_unix_timestamp()); let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id with a value of `irrelevant_merchant_id` pub fn get_irrelevant_merchant_id() -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked("irrelevant_merchant_id".to_string()); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id from String pub fn wrap(merchant_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(merchant_id)) } } impl From<MerchantId> for keymanager::Identifier { fn from(value: MerchantId) -> Self { Self::Merchant(value) } } /// All the keys that can be formed from merchant id impl MerchantId { /// get step up enabled key pub fn get_step_up_enabled_key(&self) -> String { format!("step_up_enabled_{}", self.get_string_repr()) } /// get_max_auto_retries_enabled key pub fn get_max_auto_retries_enabled(&self) -> String { format!("max_auto_retries_enabled_{}", self.get_string_repr()) } /// get_requires_cvv_key pub fn get_requires_cvv_key(&self) -> String { format!("{}_requires_cvv", self.get_string_repr()) } /// get_pm_filters_cgraph_key pub fn get_pm_filters_cgraph_key(&self) -> String { format!("pm_filters_cgraph_{}", self.get_string_repr()) } /// get_blocklist_enabled_key pub fn get_blocklist_guard_key(&self) -> String { format!("guard_blocklist_for_{}", self.get_string_repr()) } /// get_pre_routing_disabled_pm_pmt_key pub fn get_pre_routing_disabled_pm_pmt_key(&self) -> String { format!("pre_routing_disabled_pm_pmt_for_{}", self.get_string_repr()) } /// get_merchant_fingerprint_secret_key pub fn get_merchant_fingerprint_secret_key(&self) -> String { format!("fingerprint_secret_{}", self.get_string_repr()) } /// get_surcharge_dsk_key pub fn get_surcharge_dsk_key(&self) -> String { format!("surcharge_dsl_{}", self.get_string_repr()) } /// get_dsk_key pub fn get_dsl_config(&self) -> String { format!("dsl_{}", self.get_string_repr()) } /// get_creds_identifier_key pub fn get_creds_identifier_key(&self, creds_identifier: &str) -> String { format!("mcd_{}_{creds_identifier}", self.get_string_repr()) } /// get_poll_id pub fn get_poll_id(&self, unique_id: &str) -> String { format!("poll_{}_{unique_id}", self.get_string_repr()) } /// get_skip_saving_wallet_at_connector_key pub fn get_skip_saving_wallet_at_connector_key(&self) -> String { format!("skip_saving_wallet_at_connector_{}", self.get_string_repr()) } /// get_payment_config_routing_id pub fn get_payment_config_routing_id(&self) -> String { format!("payment_config_id_{}", self.get_string_repr()) } /// get_payment_method_surcharge_routing_id pub fn get_payment_method_surcharge_routing_id(&self) -> String { format!("payment_method_surcharge_id_{}", self.get_string_repr()) } /// get_webhook_config_disabled_events_key pub fn get_webhook_config_disabled_events_key(&self, connector_id: &str) -> String { format!( "whconf_disabled_events_{}_{connector_id}", self.get_string_repr() ) } /// get_should_call_gsm_payout_key pub fn get_should_call_gsm_payout_key( &self, payout_retry_type: common_enums::PayoutRetryType, ) -> String { match payout_retry_type { common_enums::PayoutRetryType::SingleConnector => format!( "should_call_gsm_single_connector_payout_{}", self.get_string_repr() ), common_enums::PayoutRetryType::MultiConnector => format!( "should_call_gsm_multiple_connector_payout_{}", self.get_string_repr() ), } } /// Get should call gsm key for payment pub fn get_should_call_gsm_key(&self) -> String { format!("should_call_gsm_{}", self.get_string_repr()) } /// get should call auth tokenization for modular authentication pub fn get_should_disable_auth_tokenization(&self) -> String { format!( "should_disable_auth_tokenization_{}", self.get_string_repr() ) } /// get_max_auto_single_connector_payout_retries_enabled_ pub fn get_max_auto_single_connector_payout_retries_enabled( &self, payout_retry_type: common_enums::PayoutRetryType, ) -> String { match payout_retry_type { common_enums::PayoutRetryType::SingleConnector => format!( "max_auto_single_connector_payout_retries_enabled_{}", self.get_string_repr() ), common_enums::PayoutRetryType::MultiConnector => format!( "max_auto_multiple_connector_payout_retries_enabled_{}", self.get_string_repr() ), } } /// allow payment update via client auth default should be false pub fn get_payment_update_enabled_for_client_auth_key(&self) -> String { format!( "payment_update_enabled_for_client_auth_{}", self.get_string_repr() ) } /// Get should perform eligibility check key for payment pub fn get_should_perform_eligibility_check_key(&self) -> String { format!("should_perform_eligibility_{}", self.get_string_repr()) } /// Get should store eligibility check data for authentication pub fn get_should_store_eligibility_check_data_for_authentication(&self) -> String { format!( "should_store_eligibility_check_data_for_authentication_{}", self.get_string_repr() ) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/profile.rs
crates/common_utils/src/id_type/profile.rs
use std::str::FromStr; crate::id_type!( ProfileId, "A type for profile_id that can be used for business profile ids" ); crate::impl_id_type_methods!(ProfileId, "profile_id"); // This is to display the `ProfileId` as ProfileId(abcd) crate::impl_debug_id_type!(ProfileId); crate::impl_try_from_cow_str_id_type!(ProfileId, "profile_id"); crate::impl_generate_id_id_type!(ProfileId, "pro"); crate::impl_serializable_secret_id_type!(ProfileId); crate::impl_queryable_id_type!(ProfileId); crate::impl_to_sql_from_sql_id_type!(ProfileId); impl crate::events::ApiEventMetric for ProfileId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::BusinessProfile { profile_id: self.clone(), }) } } impl FromStr for ProfileId { type Err = error_stack::Report<crate::errors::ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } } // This is implemented so that we can use profile id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<ProfileId> for router_env::opentelemetry::Value { fn from(val: ProfileId) -> Self { Self::from(val.0 .0 .0) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/global_id/refunds.rs
crates/common_utils/src/id_type/global_id/refunds.rs
use error_stack::ResultExt; use crate::errors; /// A global id that can be used to identify a refund #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalRefundId(super::GlobalId); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalRefundId); impl GlobalRefundId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate a new GlobalRefundId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Refund); Self(global_id) } } // TODO: refactor the macro to include this id use case as well impl TryFrom<std::borrow::Cow<'static, str>> for GlobalRefundId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let merchant_ref_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "refund_id", }, )?; Ok(Self(merchant_ref_id)) } } // TODO: refactor the macro to include this id use case as well impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalRefundId where DB: diesel::backend::Backend, super::GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalRefundId where DB: diesel::backend::Backend, super::GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { super::GlobalId::from_sql(value).map(Self) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/global_id/payment.rs
crates/common_utils/src/id_type/global_id/payment.rs
use common_enums::enums; use error_stack::ResultExt; use crate::errors; crate::global_id_type!( GlobalPaymentId, "A global id that can be used to identify a payment. The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. Example: `cell1_pay_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalPaymentId); crate::impl_to_sql_from_sql_global_id_type!(GlobalPaymentId); impl GlobalPaymentId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate a new GlobalPaymentId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Payment); Self(global_id) } /// Generate the id for revenue recovery Execute PT workflow pub fn get_execute_revenue_recovery_id( &self, task: &str, runner: enums::ProcessTrackerRunner, ) -> String { format!("{runner}_{task}_{}", self.get_string_repr()) } /// Generate a key for gift card connector pub fn get_gift_card_connector_key(&self) -> String { format!("gift_mca_{}", self.get_string_repr()) } } // TODO: refactor the macro to include this id use case as well impl TryFrom<std::borrow::Cow<'static, str>> for GlobalPaymentId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let merchant_ref_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", }, )?; Ok(Self(merchant_ref_id)) } } crate::global_id_type!( GlobalAttemptId, "A global id that can be used to identify a payment attempt" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalAttemptId); crate::impl_to_sql_from_sql_global_id_type!(GlobalAttemptId); impl GlobalAttemptId { /// Generate a new GlobalAttemptId from a cell id pub fn generate(cell_id: &super::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Attempt); Self(global_id) } /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate the id for Revenue Recovery Psync PT workflow pub fn get_psync_revenue_recovery_id( &self, task: &str, runner: enums::ProcessTrackerRunner, ) -> String { format!("{runner}_{task}_{}", self.get_string_repr()) } } impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let global_attempt_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", }, )?; Ok(Self(global_attempt_id)) } } crate::global_id_type!( GlobalAttemptGroupId, "A global id that can be used to identify a payment attempt group" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalAttemptGroupId); crate::impl_to_sql_from_sql_global_id_type!(GlobalAttemptGroupId); impl GlobalAttemptGroupId { /// Generate a new GlobalAttemptId from a cell id pub fn generate(cell_id: &super::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::AttemptGroup); Self(global_id) } /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } } impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptGroupId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let global_attempt_group_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "global_attempt_group_id", }, )?; Ok(Self(global_attempt_group_id)) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/global_id/payment_methods.rs
crates/common_utils/src/id_type/global_id/payment_methods.rs
use error_stack::ResultExt; use crate::{ errors::CustomResult, id_type::global_id::{CellId, GlobalEntity, GlobalId}, }; /// A global id that can be used to identify a payment method #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalPaymentMethodId(GlobalId); /// A global id that can be used to identify a payment method session #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalPaymentMethodSessionId(GlobalId); #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum GlobalPaymentMethodIdError { #[error("Failed to construct GlobalPaymentMethodId")] ConstructionError, } #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum GlobalPaymentMethodSessionIdError { #[error("Failed to construct GlobalPaymentMethodSessionId")] ConstructionError, } impl GlobalPaymentMethodSessionId { /// Create a new GlobalPaymentMethodSessionId from cell id information pub fn generate( cell_id: &CellId, ) -> error_stack::Result<Self, GlobalPaymentMethodSessionIdError> { let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethodSession); Ok(Self(global_id)) } /// Get the string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Construct a redis key from the id to be stored in redis pub fn get_redis_key(&self) -> String { format!("payment_method_session:{}", self.get_string_repr()) } } #[cfg(feature = "v2")] impl crate::events::ApiEventMetric for GlobalPaymentMethodSessionId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::PaymentMethodSession { payment_method_session_id: self.clone(), }) } } impl crate::events::ApiEventMetric for GlobalPaymentMethodId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some( crate::events::ApiEventsType::PaymentMethodListForPaymentMethods { payment_method_id: self.clone(), }, ) } } impl GlobalPaymentMethodId { /// Create a new GlobalPaymentMethodId from cell id information pub fn generate(cell_id: &CellId) -> error_stack::Result<Self, GlobalPaymentMethodIdError> { let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod); Ok(Self(global_id)) } /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Construct a new GlobalPaymentMethodId from a string pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> { let id = GlobalId::from_string(value.into()) .change_context(GlobalPaymentMethodIdError::ConstructionError)?; Ok(Self(id)) } } impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId where DB: diesel::backend::Backend, Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId where DB: diesel::backend::Backend, GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId where DB: diesel::backend::Backend, GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let global_id = GlobalId::from_sql(value)?; Ok(Self(global_id)) } } impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId where DB: diesel::backend::Backend, Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId where DB: diesel::backend::Backend, GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId where DB: diesel::backend::Backend, GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let global_id = GlobalId::from_sql(value)?; Ok(Self(global_id)) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/global_id/customer.rs
crates/common_utils/src/id_type/global_id/customer.rs
use crate::errors; crate::global_id_type!( GlobalCustomerId, "A global id that can be used to identify a customer. The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. Example: `cell1_cus_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalCustomerId); crate::impl_to_sql_from_sql_global_id_type!(GlobalCustomerId); impl GlobalCustomerId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate a new GlobalCustomerId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Customer); Self(global_id) } } impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: GlobalCustomerId) -> Result<Self, Self::Error> { Self::try_from(std::borrow::Cow::from(value.get_string_repr().to_owned())) } } impl crate::events::ApiEventMetric for GlobalCustomerId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Customer { customer_id: Some(self.clone()), }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/id_type/global_id/token.rs
crates/common_utils/src/id_type/global_id/token.rs
use std::borrow::Cow; use error_stack::ResultExt; use crate::errors::{CustomResult, ValidationError}; crate::global_id_type!( GlobalTokenId, "A global id that can be used to identify a token. The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. Example: `cell1_tok_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalTokenId); crate::impl_to_sql_from_sql_global_id_type!(GlobalTokenId); impl GlobalTokenId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } ///Get GlobalTokenId from a string pub fn from_string(token_string: &str) -> CustomResult<Self, ValidationError> { let token = super::GlobalId::from_string(Cow::Owned(token_string.to_string())) .change_context(ValidationError::IncorrectValueProvided { field_name: "GlobalTokenId", })?; Ok(Self(token)) } /// Generate a new GlobalTokenId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Token); Self(global_id) } } impl crate::events::ApiEventMetric for GlobalTokenId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Token { token_id: Some(self.clone()), }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types/user.rs
crates/common_utils/src/types/user.rs
/// User related types pub mod core; /// Theme related types pub mod theme; pub use core::*; pub use theme::*;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types/primitive_wrappers.rs
crates/common_utils/src/types/primitive_wrappers.rs
pub(crate) mod bool_wrappers { use serde::{Deserialize, Serialize}; /// Bool that represents if Extended Authorization is Applied or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct ExtendedAuthorizationAppliedBool(bool); impl From<bool> for ExtendedAuthorizationAppliedBool { fn from(value: bool) -> Self { Self(value) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Extended Authorization is Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct RequestExtendedAuthorizationBool(bool); impl From<bool> for RequestExtendedAuthorizationBool { fn from(value: bool) -> Self { Self(value) } } impl RequestExtendedAuthorizationBool { /// returns the inner bool value pub fn is_true(&self) -> bool { self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Extended Authorization is always Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct AlwaysRequestExtendedAuthorization(bool); impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysRequestExtendedAuthorization where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysRequestExtendedAuthorization where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types/keymanager.rs
crates/common_utils/src/types/keymanager.rs
#![allow(missing_docs)] use core::fmt; use base64::Engine; use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret}; #[cfg(feature = "encryption_service")] use router_env::logger; #[cfg(feature = "km_forward_x_request_id")] use router_env::RequestId; use rustc_hash::FxHashMap; use serde::{ de::{self, Unexpected, Visitor}, ser, Deserialize, Deserializer, Serialize, }; use crate::{ consts::BASE64_ENGINE, crypto::Encryptable, encryption::Encryption, errors::{self, CustomResult}, id_type, transformers::{ForeignFrom, ForeignTryFrom}, }; macro_rules! impl_get_tenant_for_request { ($ty:ident) => { impl GetKeymanagerTenant for $ty { fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId { match self.identifier { Identifier::User(_) | Identifier::UserAuth(_) => state.global_tenant_id.clone(), Identifier::Merchant(_) => state.tenant_id.clone(), } } } }; } #[derive(Debug, Clone)] pub struct KeyManagerState { pub tenant_id: id_type::TenantId, pub global_tenant_id: id_type::TenantId, pub enabled: bool, pub url: String, pub client_idle_timeout: Option<u64>, #[cfg(feature = "km_forward_x_request_id")] pub request_id: Option<RequestId>, #[cfg(feature = "keymanager_mtls")] pub ca: Secret<String>, #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, pub infra_values: Option<serde_json::Value>, } impl Default for KeyManagerState { fn default() -> Self { Self::new() } } impl KeyManagerState { pub fn new() -> Self { Self { tenant_id: id_type::TenantId::get_default_tenant_id(), global_tenant_id: id_type::TenantId::get_default_global_tenant_id(), enabled: Default::default(), url: String::default(), client_idle_timeout: Default::default(), #[cfg(feature = "km_forward_x_request_id")] request_id: Default::default(), #[cfg(feature = "keymanager_mtls")] ca: Default::default(), #[cfg(feature = "keymanager_mtls")] cert: Default::default(), infra_values: Default::default(), } } pub fn add_confirm_value_in_infra_values( &self, is_confirm_operation: bool, ) -> Option<serde_json::Value> { self.infra_values.clone().map(|mut infra_values| { if is_confirm_operation { infra_values.as_object_mut().map(|obj| { obj.insert( "is_confirm_operation".to_string(), serde_json::Value::Bool(true), ) }); } infra_values }) } } pub trait GetKeymanagerTenant { fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId; } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] #[serde(tag = "data_identifier", content = "key_identifier")] pub enum Identifier { User(String), Merchant(id_type::MerchantId), UserAuth(String), } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] pub struct EncryptionCreateRequest { #[serde(flatten)] pub identifier: Identifier, } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] pub struct EncryptionTransferRequest { #[serde(flatten)] pub identifier: Identifier, pub key: StrongSecret<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct DataKeyCreateResponse { #[serde(flatten)] pub identifier: Identifier, pub key_version: String, } #[derive(Serialize, Deserialize, Debug)] pub struct BatchEncryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: DecryptedDataGroup, } impl_get_tenant_for_request!(EncryptionCreateRequest); impl_get_tenant_for_request!(EncryptionTransferRequest); impl_get_tenant_for_request!(BatchEncryptDataRequest); impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest where S: Strategy<Vec<u8>>, { fn from((secret, identifier): (Secret<Vec<u8>, S>, Identifier)) -> Self { Self { identifier, data: DecryptedData(StrongSecret::new(secret.expose())), } } } impl<S> From<(FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)> for BatchEncryptDataRequest where S: Strategy<Vec<u8>>, { fn from((map, identifier): (FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)) -> Self { let group = map .into_iter() .map(|(key, value)| (key, DecryptedData(StrongSecret::new(value.expose())))) .collect(); Self { identifier, data: DecryptedDataGroup(group), } } } impl<S> From<(Secret<String, S>, Identifier)> for EncryptDataRequest where S: Strategy<String>, { fn from((secret, identifier): (Secret<String, S>, Identifier)) -> Self { Self { data: DecryptedData(StrongSecret::new(secret.expose().as_bytes().to_vec())), identifier, } } } impl<S> From<(Secret<serde_json::Value, S>, Identifier)> for EncryptDataRequest where S: Strategy<serde_json::Value>, { fn from((secret, identifier): (Secret<serde_json::Value, S>, Identifier)) -> Self { Self { data: DecryptedData(StrongSecret::new( secret.expose().to_string().as_bytes().to_vec(), )), identifier, } } } impl<S> From<(FxHashMap<String, Secret<serde_json::Value, S>>, Identifier)> for BatchEncryptDataRequest where S: Strategy<serde_json::Value>, { fn from( (map, identifier): (FxHashMap<String, Secret<serde_json::Value, S>>, Identifier), ) -> Self { let group = map .into_iter() .map(|(key, value)| { ( key, DecryptedData(StrongSecret::new( value.expose().to_string().as_bytes().to_vec(), )), ) }) .collect(); Self { data: DecryptedDataGroup(group), identifier, } } } impl<S> From<(FxHashMap<String, Secret<String, S>>, Identifier)> for BatchEncryptDataRequest where S: Strategy<String>, { fn from((map, identifier): (FxHashMap<String, Secret<String, S>>, Identifier)) -> Self { let group = map .into_iter() .map(|(key, value)| { ( key, DecryptedData(StrongSecret::new(value.expose().as_bytes().to_vec())), ) }) .collect(); Self { data: DecryptedDataGroup(group), identifier, } } } #[derive(Serialize, Deserialize, Debug)] pub struct EncryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: DecryptedData, } #[derive(Debug, Serialize, serde::Deserialize)] pub struct DecryptedDataGroup(pub FxHashMap<String, DecryptedData>); #[derive(Debug, Serialize, Deserialize)] pub struct BatchEncryptDataResponse { pub data: EncryptedDataGroup, } #[derive(Debug, Serialize, Deserialize)] pub struct EncryptDataResponse { pub data: EncryptedData, } #[derive(Debug, Serialize, serde::Deserialize)] pub struct EncryptedDataGroup(pub FxHashMap<String, EncryptedData>); #[derive(Debug)] pub struct TransientBatchDecryptDataRequest { pub identifier: Identifier, pub data: FxHashMap<String, StrongSecret<Vec<u8>>>, } #[derive(Debug)] pub struct TransientDecryptDataRequest { pub identifier: Identifier, pub data: StrongSecret<Vec<u8>>, } #[derive(Debug, Serialize, Deserialize)] pub struct BatchDecryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: FxHashMap<String, StrongSecret<String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct DecryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: StrongSecret<String>, } impl_get_tenant_for_request!(EncryptDataRequest); impl_get_tenant_for_request!(TransientBatchDecryptDataRequest); impl_get_tenant_for_request!(TransientDecryptDataRequest); impl_get_tenant_for_request!(BatchDecryptDataRequest); impl_get_tenant_for_request!(DecryptDataRequest); impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)> for FxHashMap<String, Encryptable<Secret<T, S>>> where T: Clone, S: Strategy<T> + Send, { fn foreign_from( (mut masked_data, response): (FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse), ) -> Self { response .data .0 .into_iter() .flat_map(|(k, v)| { masked_data.remove(&k).map(|inner| { ( k, Encryptable::new(inner.clone(), v.data.peek().clone().into()), ) }) }) .collect() } } impl<T, S> ForeignFrom<(Secret<T, S>, EncryptDataResponse)> for Encryptable<Secret<T, S>> where T: Clone, S: Strategy<T> + Send, { fn foreign_from((masked_data, response): (Secret<T, S>, EncryptDataResponse)) -> Self { Self::new(masked_data, response.data.data.peek().clone().into()) } } pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError>; } impl<S: Strategy<String> + Send> DecryptedDataConversion<String, S> for Encryptable<Secret<String, S>> { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError> { let string = String::from_utf8(value.clone().inner().peek().clone()).map_err(|_err| { #[cfg(feature = "encryption_service")] logger::error!("Decryption error {:?}", _err); errors::CryptoError::DecodingFailed })?; Ok(Self::new(Secret::new(string), encryption.into_inner())) } } impl<S: Strategy<serde_json::Value> + Send> DecryptedDataConversion<serde_json::Value, S> for Encryptable<Secret<serde_json::Value, S>> { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError> { let val = serde_json::from_slice(value.clone().inner().peek()).map_err(|_err| { #[cfg(feature = "encryption_service")] logger::error!("Decryption error {:?}", _err); errors::CryptoError::DecodingFailed })?; Ok(Self::new(Secret::new(val), encryption.clone().into_inner())) } } impl<S: Strategy<Vec<u8>> + Send> DecryptedDataConversion<Vec<u8>, S> for Encryptable<Secret<Vec<u8>, S>> { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError> { Ok(Self::new( Secret::new(value.clone().inner().peek().clone()), encryption.clone().into_inner(), )) } } impl<T, S> ForeignTryFrom<(Encryption, DecryptDataResponse)> for Encryptable<Secret<T, S>> where T: Clone, S: Strategy<T> + Send, Self: DecryptedDataConversion<T, S>, { type Error = error_stack::Report<errors::CryptoError>; fn foreign_try_from( (encrypted_data, response): (Encryption, DecryptDataResponse), ) -> Result<Self, Self::Error> { Self::convert(&response.data, encrypted_data) } } impl<T, S> ForeignTryFrom<(FxHashMap<String, Encryption>, BatchDecryptDataResponse)> for FxHashMap<String, Encryptable<Secret<T, S>>> where T: Clone, S: Strategy<T> + Send, Encryptable<Secret<T, S>>: DecryptedDataConversion<T, S>, { type Error = error_stack::Report<errors::CryptoError>; fn foreign_try_from( (mut encrypted_data, response): (FxHashMap<String, Encryption>, BatchDecryptDataResponse), ) -> Result<Self, Self::Error> { response .data .0 .into_iter() .map(|(k, v)| match encrypted_data.remove(&k) { Some(encrypted) => Ok((k.clone(), Encryptable::convert(&v, encrypted.clone())?)), None => Err(errors::CryptoError::DecodingFailed)?, }) .collect() } } impl From<(Encryption, Identifier)> for TransientDecryptDataRequest { fn from((encryption, identifier): (Encryption, Identifier)) -> Self { Self { data: StrongSecret::new(encryption.clone().into_inner().expose()), identifier, } } } impl From<(FxHashMap<String, Encryption>, Identifier)> for TransientBatchDecryptDataRequest { fn from((map, identifier): (FxHashMap<String, Encryption>, Identifier)) -> Self { let data = map .into_iter() .map(|(k, v)| (k, StrongSecret::new(v.clone().into_inner().expose()))) .collect(); Self { data, identifier } } } #[derive(Debug, Serialize, Deserialize)] pub struct BatchDecryptDataResponse { pub data: DecryptedDataGroup, } #[derive(Debug, Serialize, Deserialize)] pub struct DecryptDataResponse { pub data: DecryptedData, } #[derive(Clone, Debug)] pub struct DecryptedData(StrongSecret<Vec<u8>>); impl Serialize for DecryptedData { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let data = BASE64_ENGINE.encode(self.0.peek()); serializer.serialize_str(&data) } } impl<'de> Deserialize<'de> for DecryptedData { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct DecryptedDataVisitor; impl Visitor<'_> for DecryptedDataVisitor { type Value = DecryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("string of the format {version}:{base64_encoded_data}'") } fn visit_str<E>(self, value: &str) -> Result<DecryptedData, E> where E: de::Error, { let dec_data = BASE64_ENGINE.decode(value).map_err(|err| { let err = err.to_string(); E::invalid_value(Unexpected::Str(value), &err.as_str()) })?; Ok(DecryptedData(dec_data.into())) } } deserializer.deserialize_str(DecryptedDataVisitor) } } impl DecryptedData { pub fn from_data(data: StrongSecret<Vec<u8>>) -> Self { Self(data) } pub fn inner(self) -> StrongSecret<Vec<u8>> { self.0 } } #[derive(Debug)] pub struct EncryptedData { pub data: StrongSecret<Vec<u8>>, } impl Serialize for EncryptedData { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let data = String::from_utf8(self.data.peek().clone()).map_err(ser::Error::custom)?; serializer.serialize_str(data.as_str()) } } impl<'de> Deserialize<'de> for EncryptedData { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct EncryptedDataVisitor; impl Visitor<'_> for EncryptedDataVisitor { type Value = EncryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("string of the format {version}:{base64_encoded_data}'") } fn visit_str<E>(self, value: &str) -> Result<EncryptedData, E> where E: de::Error, { Ok(EncryptedData { data: StrongSecret::new(value.as_bytes().to_vec()), }) } } deserializer.deserialize_str(EncryptedDataVisitor) } } /// A trait which converts the struct to Hashmap required for encryption and back to struct pub trait ToEncryptable<T, S: Clone, E>: Sized { /// Serializes the type to a hashmap fn to_encryptable(self) -> FxHashMap<String, E>; /// Deserializes the hashmap back to the type fn from_encryptable( hashmap: FxHashMap<String, Encryptable<S>>, ) -> CustomResult<T, errors::ParsingError>; }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types/authentication.rs
crates/common_utils/src/types/authentication.rs
use crate::id_type; /// Enum for different levels of authentication #[derive( Clone, Debug, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] pub enum AuthInfo { /// OrgLevel: Authentication at the organization level OrgLevel { /// org_id: OrganizationId org_id: id_type::OrganizationId, }, /// MerchantLevel: Authentication at the merchant level MerchantLevel { /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_ids: Vec<MerchantId> merchant_ids: Vec<id_type::MerchantId>, }, /// ProfileLevel: Authentication at the profile level ProfileLevel { /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId merchant_id: id_type::MerchantId, /// profile_ids: Vec<ProfileId> profile_ids: Vec<id_type::ProfileId>, }, } /// Enum for different resource types supported in client secret #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ResourceId { /// Global Payment ID (Not exposed in api_models version of enum) Payment(id_type::GlobalPaymentId), /// Global Customer ID Customer(id_type::GlobalCustomerId), /// Global Payment Methods Session ID PaymentMethodSession(id_type::GlobalPaymentMethodSessionId), } #[cfg(feature = "v2")] impl ResourceId { /// Get string representation of enclosed ID type pub fn to_str(&self) -> &str { match self { Self::Payment(id) => id.get_string_repr(), Self::Customer(id) => id.get_string_repr(), Self::PaymentMethodSession(id) => id.get_string_repr(), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types/user/theme.rs
crates/common_utils/src/types/user/theme.rs
use common_enums::EntityType; use serde::{Deserialize, Serialize}; use crate::{ events::{ApiEventMetric, ApiEventsType}, id_type, impl_api_event_type, }; /// Enum for having all the required lineage for every level. /// Currently being used for theme related APIs and queries. #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(tag = "entity_type", rename_all = "snake_case")] pub enum ThemeLineage { /// Tenant lineage variant Tenant { /// tenant_id: TenantId tenant_id: id_type::TenantId, }, /// Org lineage variant Organization { /// tenant_id: TenantId tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, }, /// Merchant lineage variant Merchant { /// tenant_id: TenantId tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId merchant_id: id_type::MerchantId, }, /// Profile lineage variant Profile { /// tenant_id: TenantId tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId merchant_id: id_type::MerchantId, /// profile_id: ProfileId profile_id: id_type::ProfileId, }, } impl_api_event_type!(Miscellaneous, (ThemeLineage)); impl ThemeLineage { /// Constructor for ThemeLineage pub fn new( entity_type: EntityType, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, ) -> Self { match entity_type { EntityType::Tenant => Self::Tenant { tenant_id }, EntityType::Organization => Self::Organization { tenant_id, org_id }, EntityType::Merchant => Self::Merchant { tenant_id, org_id, merchant_id, }, EntityType::Profile => Self::Profile { tenant_id, org_id, merchant_id, profile_id, }, } } /// Get the entity_type from the lineage pub fn entity_type(&self) -> EntityType { match self { Self::Tenant { .. } => EntityType::Tenant, Self::Organization { .. } => EntityType::Organization, Self::Merchant { .. } => EntityType::Merchant, Self::Profile { .. } => EntityType::Profile, } } /// Get the tenant_id from the lineage pub fn tenant_id(&self) -> &id_type::TenantId { match self { Self::Tenant { tenant_id } | Self::Organization { tenant_id, .. } | Self::Merchant { tenant_id, .. } | Self::Profile { tenant_id, .. } => tenant_id, } } /// Get the org_id from the lineage pub fn org_id(&self) -> Option<&id_type::OrganizationId> { match self { Self::Tenant { .. } => None, Self::Organization { org_id, .. } | Self::Merchant { org_id, .. } | Self::Profile { org_id, .. } => Some(org_id), } } /// Get the merchant_id from the lineage pub fn merchant_id(&self) -> Option<&id_type::MerchantId> { match self { Self::Tenant { .. } | Self::Organization { .. } => None, Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => { Some(merchant_id) } } } /// Get the profile_id from the lineage pub fn profile_id(&self) -> Option<&id_type::ProfileId> { match self { Self::Tenant { .. } | Self::Organization { .. } | Self::Merchant { .. } => None, Self::Profile { profile_id, .. } => Some(profile_id), } } /// Get higher lineages from the current lineage pub fn get_same_and_higher_lineages(self) -> Vec<Self> { match &self { Self::Tenant { .. } => vec![self], Self::Organization { tenant_id, .. } => vec![ Self::Tenant { tenant_id: tenant_id.clone(), }, self, ], Self::Merchant { tenant_id, org_id, .. } => vec![ Self::Tenant { tenant_id: tenant_id.clone(), }, Self::Organization { tenant_id: tenant_id.clone(), org_id: org_id.clone(), }, self, ], Self::Profile { tenant_id, org_id, merchant_id, .. } => vec![ Self::Tenant { tenant_id: tenant_id.clone(), }, Self::Organization { tenant_id: tenant_id.clone(), org_id: org_id.clone(), }, Self::Merchant { tenant_id: tenant_id.clone(), org_id: org_id.clone(), merchant_id: merchant_id.clone(), }, self, ], } } } /// Struct for holding the theme settings for email #[derive(Debug, Clone, Default, Deserialize, Serialize)] pub struct EmailThemeConfig { /// The entity name to be used in the email pub entity_name: String, /// The URL of the entity logo to be used in the email pub entity_logo_url: String, /// The primary color to be used in the email pub primary_color: String, /// The foreground color to be used in the email pub foreground_color: String, /// The background color to be used in the email pub background_color: String, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/types/user/core.rs
crates/common_utils/src/types/user/core.rs
use diesel::{deserialize::FromSqlRow, expression::AsExpression}; use crate::id_type; /// Struct for lineageContext #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression, FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct LineageContext { /// user_id: String pub user_id: String, /// merchant_id: MerchantId pub merchant_id: id_type::MerchantId, /// role_id: String pub role_id: String, /// org_id: OrganizationId pub org_id: id_type::OrganizationId, /// profile_id: ProfileId pub profile_id: id_type::ProfileId, /// tenant_id: TenantId pub tenant_id: id_type::TenantId, } crate::impl_to_sql_from_sql_json!(LineageContext);
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/tests/percentage.rs
crates/common_utils/tests/percentage.rs
#![allow(clippy::panic_in_result_fn)] use common_utils::{errors::PercentageError, types::Percentage}; const PRECISION_2: u8 = 2; const PRECISION_0: u8 = 0; #[test] fn invalid_range_more_than_100() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("100.01".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) } #[test] fn invalid_range_less_than_0() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("-0.01".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) } #[test] fn invalid_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("-0.01ed".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) } #[test] fn valid_range() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("2.22".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.22) } let percentage = Percentage::<PRECISION_2>::from_string("0.05".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 0.05) } let percentage = Percentage::<PRECISION_2>::from_string("100.0".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 100.0) } Ok(()) } #[test] fn valid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("2.2".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.2) } let percentage = Percentage::<PRECISION_2>::from_string("2.20000".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.2) } let percentage = Percentage::<PRECISION_0>::from_string("2.0".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.0) } Ok(()) } #[test] fn invalid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("2.221".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) } #[test] fn deserialization_test_ok() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let mut decimal = 0; let mut integer = 0; // check for all percentage values from 0 to 100 while integer <= 100 { let json_string = format!( r#" {{ "percentage" : {integer}.{decimal} }} "#, ); let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(&json_string); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!( percentage.get_percentage(), format!("{integer}.{decimal}") .parse::<f32>() .unwrap_or_default() ) } if integer == 100 { break; } decimal += 1; if decimal == 100 { decimal = 0; integer += 1; } } let json_string = r#" { "percentage" : 18.7 } "#; let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 18.7) } let json_string = r#" { "percentage" : 12.0 } "#; let percentage = serde_json::from_str::<Percentage<PRECISION_0>>(json_string); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 12.0) } Ok(()) } #[test] fn deserialization_test_err() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { // invalid percentage precision let json_string = r#" { "percentage" : 12.4 } "#; let percentage = serde_json::from_str::<Percentage<PRECISION_0>>(json_string); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!(err.to_string(), "invalid value: percentage value 12.4, expected value should be a float between 0 to 100 and precise to only upto 0 decimal digits at line 4 column 9".to_string()) } // invalid percentage value let json_string = r#" { "percentage" : 123.42 } "#; let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!(err.to_string(), "invalid value: percentage value 123.42, expected value should be a float between 0 to 100 and precise to only upto 2 decimal digits at line 4 column 9".to_string()) } // missing percentage field let json_string = r#" { "percent": 22.0 } "#; let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( err.to_string(), "missing field `percentage` at line 4 column 9".to_string() ) } Ok(()) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/lib.rs
crates/payment_methods/src/lib.rs
pub mod configs; pub mod controller; pub mod core; pub mod helpers; pub mod state;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/helpers.rs
crates/payment_methods/src/helpers.rs
use api_models::{enums as api_enums, payment_methods as api}; #[cfg(feature = "v1")] use common_utils::ext_traits::AsyncExt; pub use hyperswitch_domain_models::{errors::api_error_response, payment_methods as domain}; #[cfg(feature = "v1")] use router_env::logger; use crate::state; #[cfg(feature = "v1")] pub async fn populate_bin_details_for_payment_method_create( card_details: api_models::payment_methods::CardDetail, db: Box<dyn state::PaymentMethodsStorageInterface>, ) -> api_models::payment_methods::CardDetail { let card_isin: Option<_> = Some(card_details.card_number.get_card_isin()); if card_details.card_issuer.is_some() && card_details.card_network.is_some() && card_details.card_type.is_some() && card_details.card_issuing_country.is_some() { api::CardDetail { card_issuer: card_details.card_issuer.to_owned(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.to_owned(), card_issuing_country: card_details.card_issuing_country.to_owned(), card_issuing_country_code: card_details.card_issuing_country_code.to_owned(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_cvc: card_details.card_cvc.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), } } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| logger::error!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| api::CardDetail { card_issuer: card_info.card_issuer, card_network: card_info.card_network.clone(), card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, card_issuing_country_code: card_details.card_issuing_country_code, card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_cvc: card_details.card_cvc.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), }); card_info.unwrap_or_else(|| api::CardDetail { card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, card_issuing_country_code: None, card_cvc: card_details.card_cvc.clone(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), }) } } #[cfg(feature = "v2")] pub async fn populate_bin_details_for_payment_method_create( _card_details: api_models::payment_methods::CardDetail, _db: &dyn state::PaymentMethodsStorageInterface, ) -> api_models::payment_methods::CardDetail { todo!() } pub fn validate_payment_method_type_against_payment_method( payment_method: api_enums::PaymentMethod, payment_method_type: api_enums::PaymentMethodType, ) -> bool { match payment_method { #[cfg(feature = "v1")] api_enums::PaymentMethod::Card => matches!( payment_method_type, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit ), #[cfg(feature = "v2")] api_enums::PaymentMethod::Card => matches!( payment_method_type, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit | api_enums::PaymentMethodType::Card ), api_enums::PaymentMethod::PayLater => matches!( payment_method_type, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::Alma | api_enums::PaymentMethodType::AfterpayClearpay | api_enums::PaymentMethodType::Klarna | api_enums::PaymentMethodType::PayBright | api_enums::PaymentMethodType::Atome | api_enums::PaymentMethodType::Walley | api_enums::PaymentMethodType::Breadpay | api_enums::PaymentMethodType::Flexiti | api_enums::PaymentMethodType::Payjustnow ), api_enums::PaymentMethod::Wallet => matches!( payment_method_type, api_enums::PaymentMethodType::AmazonPay | api_enums::PaymentMethodType::Bluecode | api_enums::PaymentMethodType::Paysera | api_enums::PaymentMethodType::Skrill | api_enums::PaymentMethodType::ApplePay | api_enums::PaymentMethodType::GooglePay | api_enums::PaymentMethodType::Paypal | api_enums::PaymentMethodType::AliPay | api_enums::PaymentMethodType::AliPayHk | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps | api_enums::PaymentMethodType::TouchNGo | api_enums::PaymentMethodType::Swish | api_enums::PaymentMethodType::WeChatPay | api_enums::PaymentMethodType::GoPay | api_enums::PaymentMethodType::Gcash | api_enums::PaymentMethodType::Momo | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::Mifinity | api_enums::PaymentMethodType::Paze | api_enums::PaymentMethodType::RevolutPay ), api_enums::PaymentMethod::BankRedirect => matches!( payment_method_type, api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik | api_enums::PaymentMethodType::LocalBankRedirect | api_enums::PaymentMethodType::OnlineBankingThailand | api_enums::PaymentMethodType::OnlineBankingCzechRepublic | api_enums::PaymentMethodType::OnlineBankingFinland | api_enums::PaymentMethodType::OnlineBankingFpx | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac | api_enums::PaymentMethodType::OpenBankingUk | api_enums::PaymentMethodType::OpenBankingPIS | api_enums::PaymentMethodType::OpenBanking ), api_enums::PaymentMethod::BankTransfer => matches!( payment_method_type, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::SepaBankTransfer | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Multibanco | api_enums::PaymentMethodType::Pix | api_enums::PaymentMethodType::Pse | api_enums::PaymentMethodType::PermataBankTransfer | api_enums::PaymentMethodType::BcaBankTransfer | api_enums::PaymentMethodType::BniVa | api_enums::PaymentMethodType::BriVa | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa | api_enums::PaymentMethodType::LocalBankTransfer | api_enums::PaymentMethodType::InstantBankTransfer | api_enums::PaymentMethodType::InstantBankTransferFinland | api_enums::PaymentMethodType::InstantBankTransferPoland | api_enums::PaymentMethodType::IndonesianBankTransfer ), api_enums::PaymentMethod::BankDebit => matches!( payment_method_type, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa | api_enums::PaymentMethodType::SepaGuarenteedDebit | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Becs ), api_enums::PaymentMethod::Crypto => matches!( payment_method_type, api_enums::PaymentMethodType::CryptoCurrency ), api_enums::PaymentMethod::Reward => matches!( payment_method_type, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward ), api_enums::PaymentMethod::RealTimePayment => matches!( payment_method_type, api_enums::PaymentMethodType::Fps | api_enums::PaymentMethodType::DuitNow | api_enums::PaymentMethodType::PromptPay | api_enums::PaymentMethodType::VietQr ), api_enums::PaymentMethod::Upi => matches!( payment_method_type, api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent | api_enums::PaymentMethodType::UpiQr ), api_enums::PaymentMethod::Voucher => matches!( payment_method_type, api_enums::PaymentMethodType::Boleto | api_enums::PaymentMethodType::Efecty | api_enums::PaymentMethodType::PagoEfectivo | api_enums::PaymentMethodType::RedCompra | api_enums::PaymentMethodType::RedPagos | api_enums::PaymentMethodType::Indomaret | api_enums::PaymentMethodType::Alfamart | api_enums::PaymentMethodType::Oxxo | api_enums::PaymentMethodType::SevenEleven | api_enums::PaymentMethodType::Lawson | api_enums::PaymentMethodType::MiniStop | api_enums::PaymentMethodType::FamilyMart | api_enums::PaymentMethodType::Seicomart | api_enums::PaymentMethodType::PayEasy ), api_enums::PaymentMethod::GiftCard => { matches!( payment_method_type, api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard ) } api_enums::PaymentMethod::CardRedirect => matches!( payment_method_type, api_enums::PaymentMethodType::Knet | api_enums::PaymentMethodType::Benefit | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect ), api_enums::PaymentMethod::OpenBanking => matches!( payment_method_type, api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::MobilePayment => matches!( payment_method_type, api_enums::PaymentMethodType::DirectCarrierBilling ), api_enums::PaymentMethod::NetworkToken => matches!( payment_method_type, api_enums::PaymentMethodType::NetworkToken ), } } pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } #[cfg(feature = "v1")] impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)> for api::PaymentMethodResponse { fn foreign_from( (card_details, item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod), ) -> Self { Self { merchant_id: item.merchant_id.to_owned(), customer_id: Some(item.customer_id.to_owned()), payment_method_id: item.get_id().clone(), payment_method: item.get_payment_method_type(), payment_method_type: item.get_payment_method_subtype(), card: card_details, recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: None, metadata: item.metadata, created: Some(item.created_at), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: None, client_secret: item.client_secret, } } } #[cfg(feature = "v2")] impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)> for api::PaymentMethodResponse { fn foreign_from( (_card_details, _item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod), ) -> Self { todo!() } } pub trait StorageErrorExt<T, E> { #[track_caller] fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>; #[track_caller] fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>; } impl<T> StorageErrorExt<T, api_error_response::ApiErrorResponse> for error_stack::Result<T, storage_impl::StorageError> { #[track_caller] fn to_not_found_response( self, not_found_response: api_error_response::ApiErrorResponse, ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> { self.map_err(|err| { let new_err = match err.current_context() { storage_impl::StorageError::ValueNotFound(_) => not_found_response, storage_impl::StorageError::CustomerRedacted => { api_error_response::ApiErrorResponse::CustomerRedacted } _ => api_error_response::ApiErrorResponse::InternalServerError, }; err.change_context(new_err) }) } #[track_caller] fn to_duplicate_response( self, duplicate_response: api_error_response::ApiErrorResponse, ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> { self.map_err(|err| { let new_err = match err.current_context() { storage_impl::StorageError::DuplicateValue { .. } => duplicate_response, _ => api_error_response::ApiErrorResponse::InternalServerError, }; err.change_context(new_err) }) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/state.rs
crates/payment_methods/src/state.rs
#[cfg(feature = "v1")] use common_utils::errors::CustomResult; use common_utils::types::keymanager; #[cfg(feature = "v1")] use hyperswitch_domain_models::merchant_account; use hyperswitch_domain_models::{ cards_info, customer, merchant_key_store, payment_methods as pm_domain, }; use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore}; #[async_trait::async_trait] pub trait PaymentMethodsStorageInterface: Send + Sync + dyn_clone::DynClone + pm_domain::PaymentMethodInterface<Error = errors::StorageError> + cards_info::CardsInfoInterface<Error = errors::StorageError> + customer::CustomerInterface<Error = errors::StorageError> + 'static { } dyn_clone::clone_trait_object!(PaymentMethodsStorageInterface); #[async_trait::async_trait] impl PaymentMethodsStorageInterface for MockDb {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for RouterStore<T> {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for KVRouterStore<T> {} #[derive(Clone)] pub struct PaymentMethodsState { pub store: Box<dyn PaymentMethodsStorageInterface>, pub key_store: Option<merchant_key_store::MerchantKeyStore>, pub key_manager_state: keymanager::KeyManagerState, } impl From<&PaymentMethodsState> for keymanager::KeyManagerState { fn from(state: &PaymentMethodsState) -> Self { state.key_manager_state.clone() } } #[cfg(feature = "v1")] impl PaymentMethodsState { pub async fn find_payment_method( &self, key_store: &merchant_key_store::MerchantKeyStore, merchant_account: &merchant_account::MerchantAccount, payment_method_id: String, ) -> CustomResult<pm_domain::PaymentMethod, errors::StorageError> { let db = &*self.store; match db .find_payment_method( key_store, &payment_method_id, merchant_account.storage_scheme, ) .await { Err(err) if err.current_context().is_db_not_found() => { db.find_payment_method_by_locker_id( key_store, &payment_method_id, merchant_account.storage_scheme, ) .await } Ok(pm) => Ok(pm), Err(err) => Err(err), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/core.rs
crates/payment_methods/src/core.rs
pub mod errors; pub mod migration;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/controller.rs
crates/payment_methods/src/controller.rs
use std::fmt::Debug; use api_models::payment_methods as api; #[cfg(feature = "payouts")] use api_models::payouts; #[cfg(feature = "v1")] use common_enums::enums as common_enums; #[cfg(feature = "v2")] use common_utils::encryption; use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::payment_methods::PaymentMethodVaultSourceDetails; use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption}; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] use scheduler::errors as sch_errors; use serde::{Deserialize, Serialize}; use storage_impl::{errors as storage_errors, payment_method}; use crate::core::errors; #[derive(Debug, Deserialize, Serialize)] pub struct DeleteCardResp { pub status: String, pub error_message: Option<String>, pub error_code: Option<String>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DataDuplicationCheck { Duplicated, MetaDataChanged, } #[async_trait::async_trait] pub trait PaymentMethodsController { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn create_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: &str, locker_id: Option<String>, merchant_id: &id_type::MerchantId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, payment_method_data: crypto::OptionalEncryptableValue, connector_mandate_details: Option<serde_json::Value>, status: Option<common_enums::PaymentMethodStatus>, network_transaction_id: Option<String>, payment_method_billing_address: crypto::OptionalEncryptableValue, card_scheme: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn insert_payment_method( &self, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, payment_method_billing_address: crypto::OptionalEncryptableValue, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn insert_payment_method( &self, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, payment_method_billing_address: Option<encryption::Encryption>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] async fn add_payment_method( &self, req: &api::PaymentMethodCreate, ) -> errors::PmResponse<api::PaymentMethodResponse>; #[cfg(feature = "v1")] async fn retrieve_payment_method( &self, pm: api::PaymentMethodId, ) -> errors::PmResponse<api::PaymentMethodResponse>; #[cfg(feature = "v1")] async fn delete_payment_method( &self, pm_id: api::PaymentMethodId, ) -> errors::PmResponse<api::PaymentMethodDeleteResponse>; async fn add_card_hs( &self, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, card_reference: Option<&str>, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method async fn add_card_to_locker( &self, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, card_reference: Option<&str>, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; #[cfg(feature = "payouts")] async fn add_bank_to_locker( &self, req: api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, bank: &payouts::Bank, customer_id: &id_type::CustomerId, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; #[cfg(feature = "v1")] async fn get_or_insert_payment_method( &self, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, customer_id: &id_type::CustomerId, key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] async fn get_or_insert_payment_method( &self, _req: api::PaymentMethodCreate, _resp: &mut api::PaymentMethodResponse, _customer_id: &id_type::CustomerId, _key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod> { todo!() } #[cfg(feature = "v1")] async fn get_card_details_with_locker_fallback( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<Option<api::CardDetailFromLocker>>; #[cfg(feature = "v1")] async fn get_card_details_without_locker_fallback( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<api::CardDetailFromLocker>; async fn delete_card_from_locker( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::PmResult<DeleteCardResp>; #[cfg(feature = "v1")] fn store_default_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>); #[cfg(feature = "v2")] fn store_default_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>); #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn save_network_token_and_update_payment_method( &self, req: &api::PaymentMethodMigrate, key_store: &merchant_key_store::MerchantKeyStore, network_token_data: &api_models::payment_methods::MigrateNetworkTokenData, network_token_requestor_ref_id: String, pm_id: String, ) -> errors::PmResult<bool>; #[cfg(feature = "v1")] async fn set_default_payment_method( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, payment_method_id: String, ) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>; #[cfg(feature = "v1")] async fn add_payment_method_status_update_task( &self, payment_method: &payment_methods::PaymentMethod, prev_status: common_enums::PaymentMethodStatus, curr_status: common_enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, ) -> Result<(), sch_errors::ProcessTrackerError>; #[cfg(feature = "v1")] async fn validate_merchant_connector_ids_in_connector_mandate_details( &self, key_store: &merchant_key_store::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::CommonMandateReference, merchant_id: &id_type::MerchantId, card_network: Option<common_enums::CardNetwork>, ) -> errors::PmResult<()>; #[cfg(feature = "v1")] async fn get_card_details_from_locker( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<api::CardDetailFromLocker>; } pub async fn create_encrypted_data<T>( key_manager_state: &keymanager::KeyManagerState, key_store: &merchant_key_store::MerchantKeyStore, data: T, ) -> Result< crypto::Encryptable<Secret<serde_json::Value>>, error_stack::Report<storage_errors::StorageError>, > where T: Debug + Serialize, { let key = key_store.key.get_inner().peek(); let identifier = keymanager::Identifier::Merchant(key_store.merchant_id.clone()); let encoded_data = ext_traits::Encode::encode_to_value(&data) .change_context(storage_errors::StorageError::SerializationFailed) .attach_printable("Unable to encode data")?; let secret_data = Secret::<_, masking::WithType>::new(encoded_data); let encrypted_data = type_encryption::crypto_operation( key_manager_state, type_name!(payment_method::PaymentMethod), type_encryption::CryptoOperation::Encrypt(secret_data), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .change_context(storage_errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/configs.rs
crates/payment_methods/src/configs.rs
pub mod payment_connector_required_fields; pub mod settings;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/configs/settings.rs
crates/payment_methods/src/configs/settings.rs
use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::errors::CustomResult; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use masking::Secret; use serde::{self, Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, Clone)] #[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payment_required_fields.toml pub struct RequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PaymentMethodType(pub HashMap<enums::PaymentMethodType, ConnectorFields>); #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ConnectorFields { pub fields: HashMap<enums::Connector, RequiredFieldFinal>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>); #[derive(Debug, Deserialize, Clone)] pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); #[derive(Debug, Deserialize, Clone)] pub struct BanksVector { #[serde(deserialize_with = "deserialize_hashset")] pub banks: HashSet<common_enums::enums::BankNames>, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: HashMap<String, RequiredFieldInfo>, pub non_mandate: HashMap<String, RequiredFieldInfo>, pub common: HashMap<String, RequiredFieldInfo>, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: Option<Vec<RequiredFieldInfo>>, pub non_mandate: Option<Vec<RequiredFieldInfo>>, pub common: Option<Vec<RequiredFieldInfo>>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodAuth { pub redis_expiry: i64, pub pm_auth_key: Secret<String>, } #[async_trait::async_trait] impl SecretsHandler for PaymentMethodAuth { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let payment_method_auth = value.get_inner(); let pm_auth_key = secret_management_client .get_secret(payment_method_auth.pm_auth_key.clone()) .await?; Ok(value.transition_state(|payment_method_auth| Self { pm_auth_key, ..payment_method_auth })) } } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct EligiblePaymentMethods { #[serde(deserialize_with = "deserialize_hashset")] pub sdk_eligible_payment_methods: HashSet<String>, } #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodsForMandate( pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>, ); #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodTypesForMandate( pub HashMap<enums::PaymentMethodType, SupportedConnectorsForMandate>, ); #[derive(Debug, Deserialize, Clone)] pub struct SupportedConnectorsForMandate { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone)] pub struct Mandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, pub update_mandate_supported: SupportedPaymentMethodsForMandate, } #[derive(Debug, Deserialize, Clone)] pub struct ZeroMandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, } fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { T::from_str(s.trim()).map_err(|error| { format!( "Unable to deserialize `{}` as `{}`: {error}", s.trim(), std::any::type_name::<T>() ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/configs/payment_connector_required_fields.rs
crates/payment_methods/src/configs/payment_connector_required_fields.rs
use std::collections::{HashMap, HashSet}; use api_models::{ enums::{self, Connector, FieldType}, payment_methods::RequiredFieldInfo, }; use crate::configs::settings::{ BankRedirectConfig, ConnectorFields, Mandates, RequiredFieldFinal, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, }; #[cfg(feature = "v1")] use crate::configs::settings::{PaymentMethodType, RequiredFields}; impl Default for ZeroMandates { fn default() -> Self { Self { supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::new()), } } } impl Default for Mandates { fn default() -> Self { Self { supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::from([ ( enums::PaymentMethod::PayLater, SupportedPaymentMethodTypesForMandate(HashMap::from([( enums::PaymentMethodType::Klarna, SupportedConnectorsForMandate { connector_list: HashSet::from([Connector::Adyen]), }, )])), ), ( enums::PaymentMethod::Wallet, SupportedPaymentMethodTypesForMandate(HashMap::from([ ( enums::PaymentMethodType::GooglePay, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Stripe, Connector::Adyen, Connector::Globalpay, Connector::Multisafepay, Connector::Bankofamerica, Connector::Novalnet, Connector::Noon, Connector::Cybersource, Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::ApplePay, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Stripe, Connector::Adyen, Connector::Bankofamerica, Connector::Cybersource, Connector::Novalnet, Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::SamsungPay, SupportedConnectorsForMandate { connector_list: HashSet::from([Connector::Cybersource]), }, ), ])), ), ( enums::PaymentMethod::Card, SupportedPaymentMethodTypesForMandate(HashMap::from([ ( enums::PaymentMethodType::Credit, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Aci, Connector::Adyen, Connector::Authorizedotnet, Connector::Globalpay, Connector::Worldpay, Connector::Fiuu, Connector::Multisafepay, Connector::Nexinets, Connector::Noon, Connector::Novalnet, Connector::Payme, Connector::Stripe, Connector::Bankofamerica, Connector::Cybersource, Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::Debit, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Aci, Connector::Adyen, Connector::Authorizedotnet, Connector::Globalpay, Connector::Worldpay, Connector::Fiuu, Connector::Multisafepay, Connector::Nexinets, Connector::Noon, Connector::Novalnet, Connector::Payme, Connector::Stripe, ]), }, ), ])), ), ])), update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()), } } } #[derive(Clone, serde::Serialize)] #[cfg_attr(feature = "v2", allow(dead_code))] // multiple variants are never constructed for v2 enum RequiredField { CardNumber, CardExpMonth, CardExpYear, CardCvc, CardNetwork, BillingUserFirstName, BillingUserLastName, /// display name and field type for billing first name BillingFirstName(&'static str, FieldType), /// display name and field type for billing last name BillingLastName(&'static str, FieldType), BillingEmail, Email, BillingPhone, BillingPhoneCountryCode, BillingAddressLine1, BillingAddressLine2, BillingAddressCity, BillingAddressState, BillingAddressZip, BillingCountries(Vec<&'static str>), BillingAddressCountries(Vec<&'static str>), ShippingFirstName, ShippingLastName, ShippingAddressCity, ShippingAddressState, ShippingAddressZip, ShippingCountries(Vec<&'static str>), ShippingAddressCountries(Vec<&'static str>), ShippingAddressLine1, ShippingAddressLine2, ShippingPhone, ShippingPhoneCountryCode, ShippingEmail, OpenBankingUkIssuer, OpenBankingCzechRepublicIssuer, OpenBankingPolandIssuer, OpenBankingSlovakiaIssuer, OpenBankingFpxIssuer, OpenBankingThailandIssuer, BanContactCardNumber, BanContactCardExpMonth, BanContactCardExpYear, IdealBankName, EpsBankName, EpsBankOptions(HashSet<enums::BankNames>), BlikCode, MifinityDateOfBirth, MifinityLanguagePreference(Vec<&'static str>), CryptoNetwork, CyptoPayCurrency(Vec<&'static str>), BoletoSocialSecurityNumber, UpiCollectVpaId, AchBankDebitAccountNumber, AchBankDebitRoutingNumber, AchBankDebitBankType(Vec<enums::BankType>), AchBankDebitBankAccountHolderName, SepaBankDebitIban, BacsBankDebitAccountNumber, BacsBankDebitSortCode, BecsBankDebitAccountNumber, BecsBankDebitBsbNumber, BecsBankDebitSortCode, PixKey, PixCnpj, PixCpf, PixSourceBankAccountId, GiftCardNumber, GiftCardCvc, DcbMsisdn, DcbClientUid, OrderDetailsProductName, Description, } impl RequiredField { fn to_tuple(&self) -> (String, RequiredFieldInfo) { match self { Self::CardNumber => ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: FieldType::UserCardNumber, value: None, }, ), Self::CardExpMonth => ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: FieldType::UserCardExpiryMonth, value: None, }, ), Self::CardExpYear => ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: FieldType::UserCardExpiryYear, value: None, }, ), Self::CardCvc => ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: FieldType::UserCardCvc, value: None, }, ), Self::CardNetwork => ( "payment_method_data.card.card_network".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_network".to_string(), display_name: "card_network".to_string(), field_type: FieldType::UserCardNetwork, value: None, }, ), Self::BillingUserFirstName => ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: FieldType::UserFullName, value: None, }, ), Self::BillingUserLastName => ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: FieldType::UserFullName, value: None, }, ), Self::BillingFirstName(display_name, field_type) => ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: display_name.to_string(), field_type: field_type.clone(), value: None, }, ), Self::BillingLastName(display_name, field_type) => ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: display_name.to_string(), field_type: field_type.clone(), value: None, }, ), Self::Email => ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: FieldType::UserEmailAddress, value: None, }, ), Self::BillingEmail => ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: FieldType::UserEmailAddress, value: None, }, ), Self::BillingPhone => ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: FieldType::UserPhoneNumber, value: None, }, ), Self::BillingPhoneCountryCode => ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: FieldType::UserPhoneNumberCountryCode, value: None, }, ), Self::BillingAddressLine1 => ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: FieldType::UserAddressLine1, value: None, }, ), Self::BillingAddressLine2 => ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: FieldType::UserAddressLine2, value: None, }, ), Self::BillingAddressCity => ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: FieldType::UserAddressCity, value: None, }, ), Self::BillingAddressState => ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: FieldType::UserAddressState, value: None, }, ), Self::BillingAddressZip => ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: FieldType::UserAddressPincode, value: None, }, ), Self::BillingCountries(countries) => ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::BillingAddressCountries(countries) => ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserAddressCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::ShippingFirstName => ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: FieldType::UserShippingName, value: None, }, ), Self::ShippingLastName => ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: FieldType::UserShippingName, value: None, }, ), Self::ShippingAddressCity => ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: FieldType::UserShippingAddressCity, value: None, }, ), Self::ShippingAddressState => ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: FieldType::UserShippingAddressState, value: None, }, ), Self::ShippingAddressZip => ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: FieldType::UserShippingAddressPincode, value: None, }, ), Self::ShippingCountries(countries) => ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::ShippingAddressCountries(countries) => ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserShippingAddressCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::ShippingAddressLine1 => ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: FieldType::UserShippingAddressLine1, value: None, }, ), Self::ShippingAddressLine2 => ( "shipping.address.line2".to_string(), RequiredFieldInfo { required_field: "shipping.address.line2".to_string(), display_name: "line2".to_string(), field_type: FieldType::UserShippingAddressLine2, value: None, }, ), Self::ShippingPhone => ( "shipping.phone.number".to_string(), RequiredFieldInfo { required_field: "shipping.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: FieldType::UserPhoneNumber, value: None, }, ), Self::ShippingPhoneCountryCode => ( "shipping.phone.country_code".to_string(), RequiredFieldInfo { required_field: "shipping.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: FieldType::UserPhoneNumberCountryCode, value: None, }, ), Self::ShippingEmail => ( "shipping.email".to_string(), RequiredFieldInfo { required_field: "shipping.email".to_string(), display_name: "email".to_string(), field_type: FieldType::UserEmailAddress, value: None, }, ), Self::OpenBankingUkIssuer => ( "payment_method_data.bank_redirect.open_banking_uk.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_uk.issuer" .to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::OpenBankingCzechRepublicIssuer => ( "payment_method_data.bank_redirect.open_banking_czech_republic.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_czech_republic.issuer" .to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::OpenBankingPolandIssuer => ( "payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::OpenBankingSlovakiaIssuer => ( "payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::OpenBankingFpxIssuer => ( "payment_method_data.bank_redirect.open_banking_fpx.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_fpx.issuer" .to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::OpenBankingThailandIssuer => ( "payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::BanContactCardNumber => ( "payment_method_data.bank_redirect.bancontact_card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.bancontact_card.card_number" .to_string(), display_name: "card_number".to_string(), field_type: FieldType::UserCardNumber, value: None, }, ), Self::BanContactCardExpMonth => ( "payment_method_data.bank_redirect.bancontact_card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.bancontact_card.card_exp_month" .to_string(), display_name: "card_exp_month".to_string(), field_type: FieldType::UserCardExpiryMonth, value: None, }, ), Self::BanContactCardExpYear => ( "payment_method_data.bank_redirect.bancontact_card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.bancontact_card.card_exp_year" .to_string(), display_name: "card_exp_year".to_string(), field_type: FieldType::UserCardExpiryYear, value: None, }, ), Self::IdealBankName => ( "payment_method_data.bank_redirect.ideal.bank_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(), display_name: "bank_name".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::EpsBankName => ( "payment_method_data.bank_redirect.eps.bank_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(), display_name: "bank_name".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::EpsBankOptions(bank) => ( "payment_method_data.bank_redirect.eps.bank_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(), display_name: "bank_name".to_string(), field_type: FieldType::UserBankOptions { options: bank.iter().map(|bank| bank.to_string()).collect(), }, value: None, }, ), Self::BlikCode => ( "payment_method_data.bank_redirect.blik.blik_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.blik.blik_code".to_string(), display_name: "blik_code".to_string(), field_type: FieldType::UserBlikCode, value: None, }, ), Self::MifinityDateOfBirth => ( "payment_method_data.wallet.mifinity.date_of_birth".to_string(), RequiredFieldInfo { required_field: "payment_method_data.wallet.mifinity.date_of_birth".to_string(), display_name: "date_of_birth".to_string(), field_type: FieldType::UserDateOfBirth, value: None, }, ), Self::MifinityLanguagePreference(languages) => ( "payment_method_data.wallet.mifinity.language_preference".to_string(), RequiredFieldInfo { required_field: "payment_method_data.wallet.mifinity.language_preference" .to_string(), display_name: "language_preference".to_string(), field_type: FieldType::LanguagePreference { options: languages.iter().map(|l| l.to_string()).collect(), }, value: None, }, ), Self::CryptoNetwork => ( "payment_method_data.crypto.network".to_string(), RequiredFieldInfo { required_field: "payment_method_data.crypto.network".to_string(), display_name: "network".to_string(), field_type: FieldType::UserCryptoCurrencyNetwork, value: None, }, ), Self::CyptoPayCurrency(currencies) => ( "payment_method_data.crypto.pay_currency".to_string(), RequiredFieldInfo { required_field: "payment_method_data.crypto.pay_currency".to_string(), display_name: "currency".to_string(), field_type: FieldType::UserCurrency { options: currencies.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::BoletoSocialSecurityNumber => ( "payment_method_data.voucher.boleto.social_security_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.voucher.boleto.social_security_number" .to_string(), display_name: "social_security_number".to_string(), field_type: FieldType::UserSocialSecurityNumber, value: None, }, ), Self::UpiCollectVpaId => ( "payment_method_data.upi.upi_collect.vpa_id".to_string(), RequiredFieldInfo { required_field: "payment_method_data.upi.upi_collect.vpa_id".to_string(), display_name: "vpa_id".to_string(), field_type: FieldType::UserVpaId, value: None, }, ), Self::AchBankDebitAccountNumber => ( "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number" .to_string(), display_name: "bank_account_number".to_string(), field_type: FieldType::UserBankAccountNumber, value: None, }, ), Self::AchBankDebitRoutingNumber => ( "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number" .to_string(), display_name: "bank_routing_number".to_string(), field_type: FieldType::UserBankRoutingNumber, value: None, }, ), Self::AchBankDebitBankType(bank_type) => ( "payment_method_data.bank_debit.ach_bank_debit.bank_type".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.bank_type" .to_string(), display_name: "bank_type".to_string(), field_type: FieldType::UserBankType { options: bank_type.iter().map(|bt| bt.to_string()).collect(), }, value: None, }, ), Self::AchBankDebitBankAccountHolderName => ( "payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name" .to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name"
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/core/errors.rs
crates/payment_methods/src/core/errors.rs
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError}; pub use hyperswitch_domain_models::{ api, errors::api_error_response::{self, *}, }; pub type PmResult<T> = CustomResult<T, ApiErrorResponse>; pub type PmResponse<T> = CustomResult<api::ApplicationResponse<T>, ApiErrorResponse>; pub type VaultResult<T> = CustomResult<T, VaultError>; #[derive(Debug, thiserror::Error)] pub enum VaultError { #[error("Failed to save card in card vault")] SaveCardFailed, #[error("Failed to fetch card details from card vault")] FetchCardFailed, #[error("Failed to delete card in card vault")] DeleteCardFailed, #[error("Failed to encode card vault request")] RequestEncodingFailed, #[error("Failed to deserialize card vault response")] ResponseDeserializationFailed, #[error("Failed to create payment method")] PaymentMethodCreationFailed, #[error("The given payment method is currently not supported in vault")] PaymentMethodNotSupported, #[error("The given payout method is currently not supported in vault")] PayoutMethodNotSupported, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("The card vault returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to update in PMD table")] UpdateInPaymentMethodDataTableFailed, #[error("Failed to fetch payment method in vault")] FetchPaymentMethodFailed, #[error("Failed to save payment method in vault")] SavePaymentMethodFailed, #[error("Failed to generate fingerprint")] GenerateFingerprintFailed, #[error("Failed to encrypt vault request")] RequestEncryptionFailed, #[error("Failed to decrypt vault response")] ResponseDecryptionFailed, #[error("Failed to call vault")] VaultAPIError, #[error("Failed while calling locker API")] ApiError, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/core/migration.rs
crates/payment_methods/src/core/migration.rs
use actix_multipart::form::{self, bytes, text}; use api_models::payment_methods as pm_api; use csv::Reader; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::{api, platform}; use masking::PeekInterface; use rdkafka::message::ToBytes; use router_env::{instrument, tracing}; use crate::core::errors; #[cfg(feature = "v1")] use crate::{controller as pm, state}; pub mod payment_methods; pub use payment_methods::migrate_payment_method; #[cfg(feature = "v1")] type PmMigrationResult<T> = errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>; #[cfg(feature = "v1")] pub async fn migrate_payment_methods( state: &state::PaymentMethodsState, payment_methods: Vec<pm_api::PaymentMethodRecord>, merchant_id: &common_utils::id_type::MerchantId, platform: &platform::Platform, mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, controller: &dyn pm::PaymentMethodsController, ) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> { let mut result = Vec::with_capacity(payment_methods.len()); for record in payment_methods { let req = pm_api::PaymentMethodMigrate::try_from(( &record, merchant_id.clone(), mca_ids.as_ref(), )) .map_err(|err| errors::ApiErrorResponse::InvalidRequestData { message: format!("error: {err:?}"), }) .attach_printable("record deserialization failed"); let res = match req { Ok(migrate_request) => { let res = migrate_payment_method( state, migrate_request, merchant_id, platform, controller, ) .await; match res { Ok(api::ApplicationResponse::Json(response)) => Ok(response), Err(e) => Err(e.to_string()), _ => Err("Failed to migrate payment method".to_string()), } } Err(e) => Err(e.to_string()), }; result.push(pm_api::PaymentMethodMigrationResponse::from((res, record))); } Ok(api::ApplicationResponse::Json(result)) } #[derive(Debug, form::MultipartForm)] pub struct PaymentMethodsMigrateForm { #[multipart(limit = "1MB")] pub file: bytes::Bytes, pub merchant_id: text::Text<common_utils::id_type::MerchantId>, pub merchant_connector_id: Option<text::Text<common_utils::id_type::MerchantConnectorAccountId>>, pub merchant_connector_ids: Option<text::Text<String>>, } pub struct MerchantConnectorValidator; impl MerchantConnectorValidator { pub fn parse_comma_separated_ids( ids_string: &str, ) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse> { // Estimate capacity based on comma count let capacity = ids_string.matches(',').count() + 1; let mut result = Vec::with_capacity(capacity); for id in ids_string.split(',') { let trimmed_id = id.trim(); if !trimmed_id.is_empty() { let mca_id = common_utils::id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string()) .map_err(|_| errors::ApiErrorResponse::InvalidRequestData { message: format!("Invalid merchant_connector_account_id: {trimmed_id}"), })?; result.push(mca_id); } } Ok(result) } fn validate_form_csv_conflicts( records: &[pm_api::PaymentMethodRecord], form_has_single_id: bool, form_has_multiple_ids: bool, ) -> Result<(), errors::ApiErrorResponse> { if form_has_single_id { // If form has merchant_connector_id, CSV records should not have merchant_connector_ids for (index, record) in records.iter().enumerate() { if record.merchant_connector_ids.is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Record at line {} has merchant_connector_ids but form has merchant_connector_id. Only one should be provided", index + 1 ), }); } } } if form_has_multiple_ids { // If form has merchant_connector_ids, CSV records should not have merchant_connector_id for (index, record) in records.iter().enumerate() { if record.merchant_connector_id.is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Record at line {} has merchant_connector_id but form has merchant_connector_ids. Only one should be provided", index + 1 ), }); } } } Ok(()) } } type MigrationValidationResult = Result< ( common_utils::id_type::MerchantId, Vec<pm_api::PaymentMethodRecord>, Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ), errors::ApiErrorResponse, >; impl PaymentMethodsMigrateForm { pub fn validate_and_get_payment_method_records(self) -> MigrationValidationResult { // Step 1: Validate form-level conflicts let form_has_single_id = self.merchant_connector_id.is_some(); let form_has_multiple_ids = self.merchant_connector_ids.is_some(); if form_has_single_id && form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Both merchant_connector_id and merchant_connector_ids cannot be provided" .to_string(), }); } // Ensure at least one is provided if !form_has_single_id && !form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Either merchant_connector_id or merchant_connector_ids must be provided" .to_string(), }); } // Step 2: Parse CSV let records = parse_csv(self.file.data.to_bytes()).map_err(|e| { errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), } })?; // Step 3: Validate CSV vs Form conflicts MerchantConnectorValidator::validate_form_csv_conflicts( &records, form_has_single_id, form_has_multiple_ids, )?; // Step 4: Prepare the merchant connector account IDs for return let mca_ids = if let Some(ref single_id) = self.merchant_connector_id { Some(vec![(**single_id).clone()]) } else if let Some(ref ids_string) = self.merchant_connector_ids { let parsed_ids = MerchantConnectorValidator::parse_comma_separated_ids(ids_string)?; if parsed_ids.is_empty() { None } else { Some(parsed_ids) } } else { None }; // Step 5: Return the updated structure Ok((self.merchant_id.clone(), records, mca_ids)) } } fn parse_csv(data: &[u8]) -> csv::Result<Vec<pm_api::PaymentMethodRecord>> { let mut csv_reader = Reader::from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for result in csv_reader.deserialize() { let mut record: pm_api::PaymentMethodRecord = result?; id_counter += 1; record.line_number = Some(id_counter); records.push(record); } Ok(records) } #[instrument(skip_all)] pub fn validate_card_expiry( card_exp_month: &masking::Secret<String>, card_exp_year: &masking::Secret<String>, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { let exp_month = card_exp_month .peek() .to_string() .parse::<u8>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_month", })?; ::cards::CardExpirationMonth::try_from(exp_month).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Month".to_string(), }, )?; let year_str = card_exp_year.peek().to_string(); validate_card_exp_year(year_str).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Year".to_string(), }, )?; Ok(()) } fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> { let year_str = year.to_string(); if year_str.len() == 2 || year_str.len() == 4 { year_str .parse::<u16>() .map_err(|_| errors::ValidationError::InvalidValue { message: "card_exp_year".to_string(), })?; Ok(()) } else { Err(errors::ValidationError::InvalidValue { message: "invalid card expiration year".to_string(), }) } } #[derive(Debug)] pub struct RecordMigrationStatus { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, } #[derive(Debug)] pub struct RecordMigrationStatusBuilder { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, } impl RecordMigrationStatusBuilder { pub fn new() -> Self { Self { card_migrated: None, network_token_migrated: None, connector_mandate_details_migrated: None, network_transaction_migrated: None, } } pub fn card_migrated(&mut self, card_migrated: bool) { self.card_migrated = Some(card_migrated); } pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) { self.network_token_migrated = network_token_migrated; } pub fn connector_mandate_details_migrated( &mut self, connector_mandate_details_migrated: Option<bool>, ) { self.connector_mandate_details_migrated = connector_mandate_details_migrated; } pub fn network_transaction_id_migrated(&mut self, network_transaction_migrated: Option<bool>) { self.network_transaction_migrated = network_transaction_migrated; } pub fn build(self) -> RecordMigrationStatus { RecordMigrationStatus { card_migrated: self.card_migrated, network_token_migrated: self.network_token_migrated, connector_mandate_details_migrated: self.connector_mandate_details_migrated, network_transaction_migrated: self.network_transaction_migrated, } } } impl Default for RecordMigrationStatusBuilder { fn default() -> Self { Self::new() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_methods/src/core/migration/payment_methods.rs
crates/payment_methods/src/core/migration/payment_methods.rs
use std::str::FromStr; #[cfg(feature = "v2")] use api_models::enums as api_enums; #[cfg(feature = "v1")] use api_models::enums; use api_models::payment_methods as pm_api; #[cfg(feature = "v1")] use common_utils::{ consts, crypto::Encryptable, ext_traits::{AsyncExt, ConfigExt}, generate_id, }; use common_utils::{errors::CustomResult, id_type}; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, errors::api_error_response as errors, platform, }; #[cfg(feature = "v1")] use hyperswitch_domain_models::{ext_traits::OptionExt, payment_methods as domain_pm}; use masking::PeekInterface; #[cfg(feature = "v1")] use masking::Secret; #[cfg(feature = "v1")] use router_env::{instrument, logger, tracing}; #[cfg(feature = "v1")] use serde_json::json; use storage_impl::cards_info; #[cfg(feature = "v1")] use crate::{ controller::create_encrypted_data, core::migration, helpers::{ForeignFrom, StorageErrorExt}, }; use crate::{controller::PaymentMethodsController, helpers::ForeignTryFrom, state}; #[cfg(feature = "v1")] pub async fn migrate_payment_method( state: &state::PaymentMethodsState, req: pm_api::PaymentMethodMigrate, merchant_id: &id_type::MerchantId, platform: &platform::Platform, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse> { let mut req = req; let card_details = &req.card.get_required_value("card")?; let card_number_validation_result = cards::CardNumber::from_str(card_details.card_number.peek()); let card_bin_details = populate_bin_details_for_masked_card( card_details, &*state.store, req.payment_method_type.as_ref(), ) .await?; req.card = Some(api_models::payment_methods::MigrateCardDetail { card_issuing_country: card_bin_details.issuer_country.clone(), card_network: card_bin_details.card_network.clone(), card_issuer: card_bin_details.card_issuer.clone(), card_type: card_bin_details.card_type.clone(), ..card_details.clone() }); if let Some(connector_mandate_details) = &req.connector_mandate_details { controller .validate_merchant_connector_ids_in_connector_mandate_details( platform.get_processor().get_key_store(), connector_mandate_details, merchant_id, card_bin_details.card_network.clone(), ) .await?; }; let should_require_connector_mandate_details = req.network_token.is_none(); let mut migration_status = migration::RecordMigrationStatusBuilder::new(); let resp = match card_number_validation_result { Ok(card_number) => { let payment_method_create_request = pm_api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate( card_number, &req, ); logger::debug!("Storing the card in locker and migrating the payment method"); get_client_secret_or_add_payment_method_for_migration( state, payment_method_create_request, platform.get_provider(), &mut migration_status, controller, ) .await? } Err(card_validation_error) => { logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}"); skip_locker_call_and_migrate_payment_method( state, &req, merchant_id.to_owned(), platform.get_provider(), card_bin_details.clone(), should_require_connector_mandate_details, &mut migration_status, controller, ) .await? } }; let payment_method_response = match resp { ApplicationResponse::Json(response) => response, _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the payment method response")?, }; let pm_id = payment_method_response.payment_method_id.clone(); let network_token = req.network_token.clone(); let network_token_migrated = match network_token { Some(nt_detail) => { logger::debug!("Network token migration"); let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone(); let network_token_data = &nt_detail.network_token_data; Some( controller .save_network_token_and_update_payment_method( &req, platform.get_provider().get_key_store(), network_token_data, network_token_requestor_ref_id, pm_id, ) .await .map_err(|err| logger::error!(?err, "Failed to save network token")) .ok() .unwrap_or_default(), ) } None => { logger::debug!("Network token data is not available"); None } }; migration_status.network_token_migrated(network_token_migrated); let migrate_status = migration_status.build(); Ok(ApplicationResponse::Json( pm_api::PaymentMethodMigrateResponse { payment_method_response, card_migrated: migrate_status.card_migrated, network_token_migrated: migrate_status.network_token_migrated, connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated, network_transaction_id_migrated: migrate_status.network_transaction_migrated, }, )) } #[cfg(feature = "v2")] pub async fn migrate_payment_method( _state: &state::PaymentMethodsState, _req: pm_api::PaymentMethodMigrate, _merchant_id: &id_type::MerchantId, _platform: &platform::Platform, _controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse> { todo!() } #[cfg(feature = "v1")] pub async fn populate_bin_details_for_masked_card( card_details: &api_models::payment_methods::MigrateCardDetail, db: &dyn state::PaymentMethodsStorageInterface, payment_method_type: Option<&enums::PaymentMethodType>, ) -> CustomResult<pm_api::CardDetailFromLocker, errors::ApiErrorResponse> { if let Some( // Cards enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit // Wallets | enums::PaymentMethodType::ApplePay | enums::PaymentMethodType::GooglePay, ) = payment_method_type { migration::validate_card_expiry( &card_details.card_exp_month, &card_details.card_exp_year, )?; } let card_number = card_details.card_number.clone(); let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card( card_number.peek(), ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid masked card number".to_string(), })?; let card_bin_details = if card_details.card_issuer.is_some() && card_details.card_network.is_some() && card_details.card_type.is_some() && card_details.card_issuing_country.is_some() { pm_api::CardDetailFromLocker::foreign_try_from((card_details, None))? } else { let card_info = db .get_card_info(&card_isin) .await .map_err(|error| logger::error!(card_info_error=?error)) .ok() .flatten(); pm_api::CardDetailFromLocker::foreign_try_from((card_details, card_info))? }; Ok(card_bin_details) } #[cfg(feature = "v1")] impl ForeignTryFrom<( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, )> for pm_api::CardDetailFromLocker { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (card_details, card_info): ( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, ), ) -> Result<Self, Self::Error> { let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid masked card number".to_string(), })?; if let Some(card_bin_info) = card_info { Ok(Self { scheme: card_details .card_network .clone() .or(card_bin_info.card_network.clone()) .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits.clone()), issuer_country: card_details .card_issuing_country .clone() .or(card_bin_info.card_issuing_country), issuer_country_code: card_details .card_issuing_country_code .clone() .or(card_bin_info.country_code), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_token: None, card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details .card_issuer .clone() .or(card_bin_info.card_issuer), card_network: card_details .card_network .clone() .or(card_bin_info.card_network), card_type: card_details.card_type.clone().or(card_bin_info.card_type), saved_to_locker: false, }) } else { Ok(Self { scheme: card_details .card_network .clone() .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits.clone()), issuer_country: card_details.card_issuing_country.clone(), issuer_country_code: card_details.card_issuing_country_code.clone(), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_token: None, card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker: false, }) } } } #[cfg(feature = "v2")] impl ForeignTryFrom<( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, )> for pm_api::CardDetailFromLocker { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (card_details, card_info): ( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, ), ) -> Result<Self, Self::Error> { let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid masked card number".to_string(), })?; if let Some(card_bin_info) = card_info { Ok(Self { last4_digits: Some(last4_digits.clone()), issuer_country: card_details .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() .or(card_bin_info .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten()), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details .card_issuer .clone() .or(card_bin_info.card_issuer), card_network: card_details .card_network .clone() .or(card_bin_info.card_network), card_type: card_details.card_type.clone().or(card_bin_info.card_type), saved_to_locker: false, }) } else { Ok(Self { last4_digits: Some(last4_digits.clone()), issuer_country: card_details .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker: false, }) } } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn get_client_secret_or_add_payment_method_for_migration( state: &state::PaymentMethodsState, req: pm_api::PaymentMethodCreate, provider: &platform::Provider, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { let merchant_id = provider.get_account().get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; #[cfg(not(feature = "payouts"))] let condition = req.card.is_some(); #[cfg(feature = "payouts")] let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some(); let key_manager_state = &state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| { create_encrypted_data(key_manager_state, provider.get_key_store(), billing) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; if condition { Box::pin(save_migration_payment_method( req, migration_status, controller, )) .await } else { let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let res = controller .create_payment_method( &req, &customer_id, payment_method_id.as_str(), None, merchant_id, None, None, None, connector_mandate_details.clone(), Some(enums::PaymentMethodStatus::AwaitingData), None, payment_method_billing_address, None, None, None, None, Default::default(), ) .await?; migration_status.connector_mandate_details_migrated( connector_mandate_details .clone() .and_then(|val| (val != json!({})).then_some(true)) .or_else(|| { req.connector_mandate_details .clone() .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); //card is not migrated in this case migration_status.card_migrated(false); if res.status == enums::PaymentMethodStatus::AwaitingData { controller .add_payment_method_status_update_task( &res, enums::PaymentMethodStatus::AwaitingData, enums::PaymentMethodStatus::Inactive, merchant_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to add payment method status update task in process tracker", )?; } Ok(ApplicationResponse::Json( pm_api::PaymentMethodResponse::foreign_from((None, res)), )) } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn skip_locker_call_and_migrate_payment_method( state: &state::PaymentMethodsState, req: &pm_api::PaymentMethodMigrate, merchant_id: id_type::MerchantId, provider: &platform::Provider, card: pm_api::CardDetailFromLocker, should_require_connector_mandate_details: bool, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { let db = &*state.store; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; // In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details. //if network token data is present, then connector mandate details are not mandatory let connector_mandate_details = if should_require_connector_mandate_details { let connector_mandate_details_req = req .connector_mandate_details .clone() .and_then(|c| c.payments) .clone() .get_required_value("connector mandate details")?; Some( serde_json::to_value(&connector_mandate_details_req) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector mandate details")?, ) } else { req.connector_mandate_details .clone() .and_then(|c| c.payments) .map(|mandate_details_req| { serde_json::to_value(&mandate_details_req) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector mandate details") }) .transpose()? }; let key_manager_state = &state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| { create_encrypted_data(key_manager_state, provider.get_key_store(), billing) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let customer = db .find_customer_by_customer_id_merchant_id( &customer_id, &merchant_id, provider.get_key_store(), provider.get_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let payment_method_card_details = pm_api::PaymentMethodsData::Card( pm_api::CardDetailsPaymentMethod::from((card.clone(), None)), ); let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some( create_encrypted_data( &state.into(), provider.get_key_store(), payment_method_card_details, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method card details")?, ); let payment_method_metadata: Option<serde_json::Value> = req.metadata.as_ref().map(|data| data.peek()).cloned(); let network_transaction_id = req.network_transaction_id.clone(); let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let current_time = common_utils::date_time::now(); let response = db .insert_payment_method( provider.get_key_store(), domain_pm::PaymentMethod { customer_id: customer_id.to_owned(), merchant_id: merchant_id.to_owned(), payment_method_id: payment_method_id.to_string(), locker_id: None, payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone().or(card.scheme.clone()), metadata: payment_method_metadata.map(Secret::new), payment_method_data: payment_method_data_encrypted, connector_mandate_details: connector_mandate_details.clone(), customer_acceptance: None, client_secret: None, status: enums::PaymentMethodStatus::Active, network_transaction_id: network_transaction_id.clone(), payment_method_issuer_code: None, accepted_currency: None, token: None, cardholder_name: None, issuer_name: None, issuer_country: None, payer_country: None, is_stored: None, swift_code: None, direct_debit_token: None, created_at: current_time, last_modified: current_time, last_used_at: current_time, payment_method_billing_address, updated_by: None, version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, vault_source_details: Default::default(), created_by: None, last_modified_by: None, }, provider.get_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; logger::debug!("Payment method inserted in db"); migration_status.network_transaction_id_migrated( network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), ); migration_status.connector_mandate_details_migrated( connector_mandate_details .clone() .and_then(|val| if val == json!({}) { None } else { Some(true) }) .or_else(|| { req.connector_mandate_details.clone().and_then(|val| { val.payments .and_then(|payin_val| (!payin_val.0.is_empty()).then_some(false)) }) }), ); if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = controller .set_default_payment_method(&merchant_id, &customer_id, payment_method_id.to_owned()) .await .map_err(|error| logger::error!(?error, "Failed to set the payment method as default")); } Ok(ApplicationResponse::Json( pm_api::PaymentMethodResponse::foreign_from((Some(card), response)), )) } // need to discuss regarding the migration APIs for v2 #[cfg(feature = "v2")] pub async fn skip_locker_call_and_migrate_payment_method( _state: state::PaymentMethodsState, _req: &pm_api::PaymentMethodMigrate, _merchant_id: id_type::MerchantId, _provider: &platform::Provider, _card: pm_api::CardDetailFromLocker, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { todo!() } pub fn get_card_bin_and_last4_digits_for_masked_card( masked_card_number: &str, ) -> Result<(String, String), cards::CardNumberValidationErr> { let last4_digits = masked_card_number .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(); let card_isin = masked_card_number.chars().take(6).collect::<String>(); cards::validate::validate_card_number_chars(&card_isin) .and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?; Ok((card_isin, last4_digits)) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn save_migration_payment_method( req: pm_api::PaymentMethodCreate, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; let network_transaction_id = req.network_transaction_id.clone(); let res = controller.add_payment_method(&req).await?; migration_status.card_migrated(true); migration_status.network_transaction_id_migrated( network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), ); migration_status.connector_mandate_details_migrated( connector_mandate_details .and_then(|val| if val == json!({}) { None } else { Some(true) }) .or_else(|| { req.connector_mandate_details .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); Ok(res) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/config.rs
crates/storage_impl/src/config.rs
use common_utils::DbConnectionParams; use hyperswitch_domain_models::master_key::MasterKeyInterface; use masking::{PeekInterface, Secret}; use crate::{kv_router_store, DatabaseStore, MockDb, RouterStore}; #[derive(Debug, Clone, serde::Deserialize)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } impl DbConnectionParams for Database { fn get_username(&self) -> &str { &self.username } fn get_password(&self) -> Secret<String> { self.password.clone() } fn get_host(&self) -> &str { &self.host } fn get_port(&self) -> u16 { self.port } fn get_dbname(&self) -> &str { &self.dbname } } #[derive(Debug, serde::Deserialize, Clone, Copy, Default)] #[serde(rename_all = "PascalCase")] pub enum QueueStrategy { #[default] Fifo, Lifo, } impl From<QueueStrategy> for bb8::QueueStrategy { fn from(value: QueueStrategy) -> Self { match value { QueueStrategy::Fifo => Self::Fifo, QueueStrategy::Lifo => Self::Lifo, } } } impl Default for Database { fn default() -> Self { Self { username: String::new(), password: Secret::<String>::default(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, queue_strategy: QueueStrategy::default(), min_idle: None, max_lifetime: None, } } } impl<T: DatabaseStore> MasterKeyInterface for kv_router_store::KVRouterStore<T> { fn get_master_key(&self) -> &[u8] { self.master_key().peek() } } impl<T: DatabaseStore> MasterKeyInterface for RouterStore<T> { fn get_master_key(&self) -> &[u8] { self.master_key().peek() } } /// Default dummy key for MockDb impl MasterKeyInterface for MockDb { fn get_master_key(&self) -> &[u8] { self.master_key() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/errors.rs
crates/storage_impl/src/errors.rs
pub use common_enums::{ApiClientError, ApplicationError, ApplicationResult}; pub use redis_interface::errors::RedisError; use crate::store::errors::DatabaseError; pub type StorageResult<T> = error_stack::Result<T, StorageError>; #[derive(Debug, thiserror::Error)] pub enum StorageError { #[error("Initialization Error")] InitializationError, #[error("DatabaseError: {0:?}")] DatabaseError(error_stack::Report<DatabaseError>), #[error("ValueNotFound: {0}")] ValueNotFound(String), #[error("DuplicateValue: {entity} already exists {key:?}")] DuplicateValue { entity: &'static str, key: Option<String>, }, #[error("Timed out while trying to connect to the database")] DatabaseConnectionError, #[error("KV error")] KVError, #[error("Serialization failure")] SerializationFailed, #[error("MockDb error")] MockDbError, #[error("Kafka error")] KafkaError, #[error("Customer with this id is Redacted")] CustomerRedacted, #[error("Deserialization failure")] DeserializationFailed, #[error("Error while encrypting data")] EncryptionError, #[error("Error while decrypting data from database")] DecryptionError, #[error("RedisError: {0:?}")] RedisError(error_stack::Report<RedisError>), } impl From<error_stack::Report<RedisError>> for StorageError { fn from(err: error_stack::Report<RedisError>) -> Self { match err.current_context() { RedisError::NotFound => Self::ValueNotFound("redis value not found".to_string()), RedisError::JsonSerializationFailed => Self::SerializationFailed, RedisError::JsonDeserializationFailed => Self::DeserializationFailed, _ => Self::RedisError(err), } } } impl From<diesel::result::Error> for StorageError { fn from(err: diesel::result::Error) -> Self { Self::from(error_stack::report!(DatabaseError::from(err))) } } impl From<error_stack::Report<DatabaseError>> for StorageError { fn from(err: error_stack::Report<DatabaseError>) -> Self { match err.current_context() { DatabaseError::DatabaseConnectionError => Self::DatabaseConnectionError, DatabaseError::NotFound => Self::ValueNotFound(String::from("db value not found")), DatabaseError::UniqueViolation => Self::DuplicateValue { entity: "db entity", key: None, }, _ => Self::DatabaseError(err), } } } impl StorageError { pub fn is_db_not_found(&self) -> bool { match self { Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound), Self::ValueNotFound(_) => true, Self::RedisError(err) => matches!(err.current_context(), RedisError::NotFound), _ => false, } } pub fn is_db_unique_violation(&self) -> bool { match self { Self::DatabaseError(err) => { matches!(err.current_context(), DatabaseError::UniqueViolation,) } Self::DuplicateValue { .. } => true, _ => false, } } } pub trait RedisErrorExt { #[track_caller] fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError>; } impl RedisErrorExt for error_stack::Report<RedisError> { fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError> { match self.current_context() { RedisError::NotFound => self.change_context(StorageError::ValueNotFound(format!( "Data does not exist for key {key}", ))), RedisError::SetNxFailed | RedisError::SetAddMembersFailed => { self.change_context(StorageError::DuplicateValue { entity: "redis", key: Some(key.to_string()), }) } _ => self.change_context(StorageError::KVError), } } } #[derive(Debug, thiserror::Error, PartialEq)] pub enum ConnectorError { #[error("Error while obtaining URL for the integration")] FailedToObtainIntegrationUrl, #[error("Failed to encode connector request")] RequestEncodingFailed, #[error("Request encoding failed : {0}")] RequestEncodingFailedWithReason(String), #[error("Parsing failed")] ParsingFailed, #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, #[error("Failed to execute a processing step: {0:?}")] ProcessingStepFailed(Option<bytes::Bytes>), #[error("The connector returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to parse custom routing rules from merchant account")] RoutingRulesParsingError, #[error("Failed to obtain preferred connector from merchant account")] FailedToObtainPreferredConnector, #[error("An invalid connector name was provided")] InvalidConnectorName, #[error("An invalid Wallet was used")] InvalidWallet, #[error("Failed to handle connector response")] ResponseHandlingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("Missing required fields: {field_names:?}")] MissingRequiredFields { field_names: Vec<&'static str> }, #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Failed to obtain certificate")] FailedToObtainCertificate, #[error("Connector meta data not found")] NoConnectorMetaData, #[error("Failed to obtain certificate key")] FailedToObtainCertificateKey, #[error("This step has not been implemented for: {0}")] NotImplemented(String), #[error("{message} is not supported by {connector}")] NotSupported { message: String, connector: &'static str, payment_experience: String, }, #[error("{flow} flow not supported by {connector} connector")] FlowNotSupported { flow: String, connector: String }, #[error("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}'")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, #[error("Capture method not supported")] CaptureMethodNotSupported, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] MissingConnectorRefundID, #[error("Webhooks not implemented for this connector")] WebhooksNotImplemented, #[error("Failed to decode webhook event body")] WebhookBodyDecodingFailed, #[error("Signature not found for incoming webhook")] WebhookSignatureNotFound, #[error("Failed to verify webhook source")] WebhookSourceVerificationFailed, #[error("Could not find merchant secret in DB for incoming webhook source verification")] WebhookVerificationSecretNotFound, #[error("Incoming webhook object reference ID not found")] WebhookReferenceIdNotFound, #[error("Incoming webhook event type not found")] WebhookEventTypeNotFound, #[error("Incoming webhook event resource object not found")] WebhookResourceObjectNotFound, #[error("Could not respond to the incoming webhook event")] WebhookResponseEncodingFailed, #[error("Invalid Date/time format")] InvalidDateFormat, #[error("Date Formatting Failed")] DateFormattingFailed, #[error("Invalid Data format")] InvalidDataFormat { field_name: &'static str }, #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] MismatchedPaymentData, #[error("Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error("Failed to parse Wallet token")] InvalidWalletToken { wallet_name: String }, #[error("Missing Connector Related Transaction ID")] MissingConnectorRelatedTransactionID { id: String }, #[error("File Validation failed")] FileValidationFailed { reason: String }, #[error("Missing 3DS redirection payload: {field_name}")] MissingConnectorRedirectionPayload { field_name: &'static str }, } #[derive(Debug, thiserror::Error)] pub enum HealthCheckDBError { #[error("Error while connecting to database")] DBError, #[error("Error while writing to database")] DBWriteError, #[error("Error while reading element in the database")] DBReadError, #[error("Error while deleting element in the database")] DBDeleteError, #[error("Unpredictable error occurred")] UnknownError, #[error("Error in database transaction")] TransactionError, #[error("Error while executing query in Sqlx Analytics")] SqlxAnalyticsError, #[error("Error while executing query in Clickhouse Analytics")] ClickhouseAnalyticsError, #[error("Error while executing query in Opensearch")] OpensearchError, } impl From<diesel::result::Error> for HealthCheckDBError { fn from(error: diesel::result::Error) -> Self { match error { diesel::result::Error::DatabaseError(_, _) => Self::DBError, diesel::result::Error::RollbackErrorOnCommit { .. } | diesel::result::Error::RollbackTransaction | diesel::result::Error::AlreadyInTransaction | diesel::result::Error::NotInTransaction | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, _ => Self::UnknownError, } } } #[derive(Debug, thiserror::Error)] pub enum HealthCheckRedisError { #[error("Failed to establish Redis connection")] RedisConnectionError, #[error("Failed to set key value in Redis")] SetFailed, #[error("Failed to get key value in Redis")] GetFailed, #[error("Failed to delete key value in Redis")] DeleteFailed, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckLockerError { #[error("Failed to establish Locker connection")] FailedToCallLocker, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckGRPCServiceError { #[error("Failed to establish connection with gRPC service")] FailedToCallService, } #[derive(thiserror::Error, Debug, Clone)] pub enum RecoveryError { #[error("Failed to make a recovery payment")] PaymentCallFailed, #[error("Encountered a Process Tracker Task Failure")] ProcessTrackerFailure, #[error("The encountered task is invalid")] InvalidTask, #[error("The Process Tracker data was not found")] ValueNotFound, #[error("Failed to update billing connector")] RecordBackToBillingConnectorFailed, #[error("Failed to fetch billing connector account id")] BillingMerchantConnectorAccountIdNotFound, #[error("Failed to generate payment sync data")] PaymentsResponseGenerationFailed, #[error("Outgoing Webhook Failed")] RevenueRecoveryOutgoingWebhookFailed, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckDecisionEngineError { #[error("Failed to establish Decision Engine connection")] FailedToCallDecisionEngineService, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckUnifiedConnectorServiceError { #[error("Failed to establish Unified Connector Service connection")] FailedToCallUnifiedConnectorService, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/callback_mapper.rs
crates/storage_impl/src/callback_mapper.rs
use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper; use hyperswitch_domain_models::callback_mapper::CallbackMapper; use crate::DataModelExt; impl DataModelExt for CallbackMapper { type StorageModel = DieselCallbackMapper; fn to_storage_model(self) -> Self::StorageModel { DieselCallbackMapper { id: self.id, type_: self.callback_mapper_id_type, data: self.data, created_at: self.created_at, last_modified_at: self.last_modified_at, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { id: storage_model.id, callback_mapper_id_type: storage_model.type_, data: storage_model.data, created_at: storage_model.created_at, last_modified_at: storage_model.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/storage_impl/src/lib.rs
crates/storage_impl/src/lib.rs
use std::{fmt::Debug, sync::Arc}; use common_utils::types::TenantConfig; use diesel_models as store; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use masking::StrongSecret; use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore}; mod address; pub mod business_profile; pub mod callback_mapper; pub mod cards_info; pub mod config; pub mod configs; pub mod connection; pub mod customers; pub mod database; pub mod errors; pub mod invoice; pub mod kv_router_store; pub mod lookup; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod metrics; pub mod mock_db; pub mod payment_method; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod platform_wrapper; pub mod redis; pub mod refund; mod reverse_lookup; pub mod subscription; pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use database::store::PgPool; pub mod tokenization; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; pub use mock_db::MockDb; use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply}; #[cfg(not(feature = "payouts"))] pub use crate::database::store::Store; pub use crate::{database::store::DatabaseStore, errors::StorageError}; #[derive(Debug, Clone)] pub struct RouterStore<T: DatabaseStore> { db_store: T, cache_store: Arc<RedisStore>, master_encryption_key: StrongSecret<Vec<u8>>, pub request_id: Option<String>, key_manager_state: Option<KeyManagerState>, } impl<T: DatabaseStore> RouterStore<T> { pub fn set_key_manager_state(&mut self, state: KeyManagerState) { self.key_manager_state = Some(state); } fn get_keymanager_state(&self) -> Result<&KeyManagerState, StorageError> { self.key_manager_state .as_ref() .ok_or_else(|| StorageError::DecryptionError) } } #[async_trait::async_trait] impl<T: DatabaseStore> DatabaseStore for RouterStore<T> where T::Config: Send, { type Config = ( T::Config, redis_interface::RedisSettings, StrongSecret<Vec<u8>>, tokio::sync::oneshot::Sender<()>, &'static str, ); async fn new( config: Self::Config, tenant_config: &dyn TenantConfig, test_transaction: bool, key_manager_state: Option<KeyManagerState>, ) -> error_stack::Result<Self, StorageError> { let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) = config; if test_transaction { Self::test_store( db_conf, tenant_config, &cache_conf, encryption_key, key_manager_state, ) .await .attach_printable("failed to create test router store") } else { Self::from_config( db_conf, tenant_config, encryption_key, Self::cache_store(&cache_conf, cache_error_signal).await?, inmemory_cache_stream, key_manager_state, ) .await .attach_printable("failed to create store") } } fn get_master_pool(&self) -> &PgPool { self.db_store.get_master_pool() } fn get_replica_pool(&self) -> &PgPool { self.db_store.get_replica_pool() } fn get_accounts_master_pool(&self) -> &PgPool { self.db_store.get_accounts_master_pool() } fn get_accounts_replica_pool(&self) -> &PgPool { self.db_store.get_accounts_replica_pool() } } impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> { fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> { self.cache_store.get_redis_conn() } } impl<T: DatabaseStore> RouterStore<T> { pub async fn from_config( db_conf: T::Config, tenant_config: &dyn TenantConfig, encryption_key: StrongSecret<Vec<u8>>, cache_store: Arc<RedisStore>, inmemory_cache_stream: &str, key_manager_state: Option<KeyManagerState>, ) -> error_stack::Result<Self, StorageError> { let db_store = T::new(db_conf, tenant_config, false, key_manager_state.clone()).await?; let redis_conn = cache_store.redis_conn.clone(); let cache_store = Arc::new(RedisStore { redis_conn: Arc::new(RedisConnectionPool::clone( &redis_conn, tenant_config.get_redis_key_prefix(), )), }); cache_store .redis_conn .subscribe(inmemory_cache_stream) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to subscribe to inmemory cache stream")?; Ok(Self { db_store, cache_store, master_encryption_key: encryption_key, request_id: None, key_manager_state, }) } pub async fn cache_store( cache_conf: &redis_interface::RedisSettings, cache_error_signal: tokio::sync::oneshot::Sender<()>, ) -> error_stack::Result<Arc<RedisStore>, StorageError> { let cache_store = RedisStore::new(cache_conf) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to create cache store")?; cache_store.set_error_callback(cache_error_signal); Ok(Arc::new(cache_store)) } pub fn master_key(&self) -> &StrongSecret<Vec<u8>> { &self.master_encryption_key } pub async fn call_database<D, R, M>( &self, key_store: &MerchantKeyStore, execute_query: R, ) -> error_stack::Result<D, StorageError> where D: Debug + Sync + Conversion, R: futures::Future<Output = error_stack::Result<M, diesel_models::errors::DatabaseError>> + Send, M: ReverseConversion<D>, { execute_query .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } pub async fn find_optional_resource<D, R, M>( &self, key_store: &MerchantKeyStore, execute_query_fut: R, ) -> error_stack::Result<Option<D>, StorageError> where D: Debug + Sync + Conversion, R: futures::Future< Output = error_stack::Result<Option<M>, diesel_models::errors::DatabaseError>, > + Send, M: ReverseConversion<D>, { match execute_query_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? { Some(resource) => Ok(Some( resource .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, )), None => Ok(None), } } pub async fn find_resources<D, R, M>( &self, key_store: &MerchantKeyStore, execute_query: R, ) -> error_stack::Result<Vec<D>, StorageError> where D: Debug + Sync + Conversion, R: futures::Future< Output = error_stack::Result<Vec<M>, diesel_models::errors::DatabaseError>, > + Send, M: ReverseConversion<D>, { let resource_futures = execute_query .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? .into_iter() .map(|resource| async { resource .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .collect::<Vec<_>>(); let resources = futures::future::try_join_all(resource_futures).await?; Ok(resources) } /// # Panics /// /// Will panic if `CONNECTOR_AUTH_FILE_PATH` is not set pub async fn test_store( db_conf: T::Config, tenant_config: &dyn TenantConfig, cache_conf: &redis_interface::RedisSettings, encryption_key: StrongSecret<Vec<u8>>, key_manager_state: Option<KeyManagerState>, ) -> error_stack::Result<Self, StorageError> { // TODO: create an error enum and return proper error here let db_store = T::new(db_conf, tenant_config, true, key_manager_state.clone()).await?; let cache_store = RedisStore::new(cache_conf) .await .change_context(StorageError::InitializationError) .attach_printable("failed to create redis cache")?; Ok(Self { db_store, cache_store: Arc::new(cache_store), master_encryption_key: encryption_key, request_id: None, key_manager_state, }) } } // TODO: This should not be used beyond this crate // Remove the pub modified once StorageScheme usage is completed pub trait DataModelExt { type StorageModel; fn to_storage_model(self) -> Self::StorageModel; fn from_storage_model(storage_model: Self::StorageModel) -> Self; } pub(crate) fn diesel_error_to_data_error( diesel_error: diesel_models::errors::DatabaseError, ) -> StorageError { match diesel_error { diesel_models::errors::DatabaseError::DatabaseConnectionError => { StorageError::DatabaseConnectionError } diesel_models::errors::DatabaseError::NotFound => { StorageError::ValueNotFound("Value not found".to_string()) } diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue { entity: "entity ", key: None, }, _ => StorageError::DatabaseError(error_stack::report!(diesel_error)), } } #[async_trait::async_trait] pub trait UniqueConstraints { fn unique_constraints(&self) -> Vec<String>; fn table_name(&self) -> &str; async fn check_for_constraints( &self, redis_conn: &Arc<RedisConnectionPool>, ) -> CustomResult<(), RedisError> { let constraints = self.unique_constraints(); let sadd_result = redis_conn .sadd( &format!("unique_constraint:{}", self.table_name()).into(), constraints, ) .await?; match sadd_result { SaddReply::KeyNotSet => Err(error_stack::report!(RedisError::SetAddMembersFailed)), SaddReply::KeySet => Ok(()), } } } impl UniqueConstraints for diesel_models::Address { fn unique_constraints(&self) -> Vec<String> { vec![format!("address_{}", self.address_id)] } fn table_name(&self) -> &str { "Address" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentIntent { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "PaymentIntent" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentIntent { #[cfg(feature = "v1")] fn unique_constraints(&self) -> Vec<String> { vec![format!( "pi_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr() )] } #[cfg(feature = "v2")] fn unique_constraints(&self) -> Vec<String> { vec![format!("pi_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "PaymentIntent" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( "pa_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id )] } fn table_name(&self) -> &str { "PaymentAttempt" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!("pa_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "PaymentAttempt" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![format!( "refund_{}_{}", self.merchant_id.get_string_repr(), self.refund_id )] } fn table_name(&self) -> &str { "Refund" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "Refund" } } impl UniqueConstraints for diesel_models::ReverseLookup { fn unique_constraints(&self) -> Vec<String> { vec![format!("reverselookup_{}", self.lookup_id)] } fn table_name(&self) -> &str { "ReverseLookup" } } #[cfg(feature = "payouts")] impl UniqueConstraints for diesel_models::Payouts { fn unique_constraints(&self) -> Vec<String> { vec![format!( "po_{}_{}", self.merchant_id.get_string_repr(), self.payout_id.get_string_repr() )] } fn table_name(&self) -> &str { "Payouts" } } #[cfg(feature = "payouts")] impl UniqueConstraints for diesel_models::PayoutAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( "poa_{}_{}", self.merchant_id.get_string_repr(), self.payout_attempt_id )] } fn table_name(&self) -> &str { "PayoutAttempt" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentMethod { fn unique_constraints(&self) -> Vec<String> { vec![format!("paymentmethod_{}", self.payment_method_id)] } fn table_name(&self) -> &str { "PaymentMethod" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentMethod { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "PaymentMethod" } } impl UniqueConstraints for diesel_models::Mandate { fn unique_constraints(&self) -> Vec<String> { vec![format!( "mand_{}_{}", self.merchant_id.get_string_repr(), self.mandate_id )] } fn table_name(&self) -> &str { "Mandate" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Customer { fn unique_constraints(&self) -> Vec<String> { vec![format!( "customer_{}_{}", self.customer_id.get_string_repr(), self.merchant_id.get_string_repr(), )] } fn table_name(&self) -> &str { "Customer" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::Customer { fn unique_constraints(&self) -> Vec<String> { vec![format!("customer_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "Customer" } } #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {} #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl UniqueConstraints for diesel_models::tokenization::Tokenization { fn unique_constraints(&self) -> Vec<String> { vec![format!("id_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "tokenization" } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/address.rs
crates/storage_impl/src/address.rs
use diesel_models::address::Address; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Address {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/customers.rs
crates/storage_impl/src/customers.rs
use common_utils::{id_type, pii}; use diesel_models::{customers, kv}; use error_stack::ResultExt; use futures::future::try_join_all; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, customer as domain, merchant_key_store::MerchantKeyStore, }; use masking::PeekInterface; use router_env::{instrument, tracing}; use crate::{ diesel_error_to_data_error, errors::StorageError, kv_router_store, redis::kv_store::{decide_storage_scheme, KvStorePartition, Op, PartitionKey}, store::enums::MerchantStorageScheme, utils::{pg_connection_read, pg_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, }; impl KvStorePartition for customers::Customer {} #[cfg(feature = "v2")] mod label { use common_utils::id_type; pub(super) const MODEL_NAME: &str = "customer_v2"; pub(super) const CLUSTER_LABEL: &str = "cust"; pub(super) fn get_global_id_label(global_customer_id: &id_type::GlobalCustomerId) -> String { format!( "customer_global_id_{}", global_customer_id.get_string_repr() ) } pub(super) fn get_merchant_scoped_id_label( merchant_id: &id_type::MerchantId, merchant_reference_id: &id_type::CustomerId, ) -> String { format!( "customer_mid_{}_mrefid_{}", merchant_id.get_string_repr(), merchant_reference_id.get_string_repr() ) } } #[async_trait::async_trait] impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_result = self .find_optional_resource_by_id( key_store, storage_scheme, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", customer_id.get_string_repr()), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, ), ) .await?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(Some(customer)), }) } #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; self.find_optional_resource_by_id( key_store, storage_scheme, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", customer_id.get_string_repr()), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, ), ) .await } #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_result = self .find_optional_resource_by_id( key_store, storage_scheme, customers::Customer::find_optional_by_merchant_id_merchant_reference_id( &conn, merchant_reference_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", merchant_reference_id.get_string_repr()), PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }, ), ) .await?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(Some(customer)), }) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(StorageError::EncryptionError)?; let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); self.update_resource( key_store, storage_scheme, customers::Customer::update_by_customer_id_merchant_id( &conn, customer_id.clone(), merchant_id.clone(), customer_update.clone().into(), ), updated_customer, kv_router_store::UpdateResourceParams { updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems { orig: customer.clone(), update_data: customer_update.clone().into(), }), operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()), }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let result: domain::Customer = self .find_resource_by_id( key_store, storage_scheme, customers::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", merchant_reference_id.get_string_repr()), PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }, ), ) .await?; match result.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(result), } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let result: domain::Customer = self .find_resource_by_id( key_store, storage_scheme, customers::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", customer_id.get_string_repr()), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, ), ) .await?; match result.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(result), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, StorageError> { self.router_store .list_customers_by_merchant_id(merchant_id, key_store, constraints) .await } #[instrument(skip_all)] async fn list_customers_by_merchant_id_with_count( &self, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> { self.router_store .list_customers_by_merchant_id_with_count(merchant_id, key_store, constraints) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: domain::Customer, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let id = customer_data.id.clone(); let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let identifier = format!("cust_{}", id.get_string_repr()); let mut new_customer = customer_data .construct_new() .await .change_context(StorageError::EncryptionError)?; let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(decided_storage_scheme); let mut reverse_lookups = Vec::new(); if let Some(ref merchant_ref_id) = new_customer.merchant_reference_id { let reverse_lookup_merchant_scoped_id = label::get_merchant_scoped_id_label(&new_customer.merchant_id, merchant_ref_id); reverse_lookups.push(reverse_lookup_merchant_scoped_id); } self.insert_resource( key_store, decided_storage_scheme, new_customer.clone().insert(&conn), new_customer.clone().into(), kv_router_store::InsertResourceParams { insertable: kv::Insertable::Customer(new_customer.clone()), reverse_lookups, identifier, key, resource_type: "customer", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: domain::Customer, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let key = PartitionKey::MerchantIdCustomerId { merchant_id: &customer_data.merchant_id.clone(), customer_id: &customer_data.customer_id.clone(), }; let identifier = format!("cust_{}", customer_data.customer_id.get_string_repr()); let mut new_customer = customer_data .construct_new() .await .change_context(StorageError::EncryptionError)?; let storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(storage_scheme); let customer = new_customer.clone().into(); self.insert_resource( key_store, storage_scheme, new_customer.clone().insert(&conn), customer, kv_router_store::InsertResourceParams { insertable: kv::Insertable::Customer(new_customer.clone()), reverse_lookups: vec![], identifier, key, resource_type: "customer", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_customer_by_customer_id_merchant_id(customer_id, merchant_id) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, id: &id_type::GlobalCustomerId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let result: domain::Customer = self .find_resource_by_id( key_store, storage_scheme, customers::Customer::find_by_global_id(&conn, id), kv_router_store::FindResourceBy::Id( format!("cust_{}", id.get_string_repr()), PartitionKey::GlobalId { id: id.get_string_repr(), }, ), ) .await?; if result.status == common_enums::DeleteStatus::Redacted { Err(StorageError::CustomerRedacted)? } else { Ok(result) } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_customer_by_global_id( &self, id: &id_type::GlobalCustomerId, customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(StorageError::EncryptionError)?; let database_call = customers::Customer::update_by_id(&conn, id.clone(), customer_update.clone().into()); let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); self.update_resource( key_store, storage_scheme, database_call, diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()), kv_router_store::UpdateResourceParams { updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems { orig: customer.clone(), update_data: customer_update.into(), }), operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()), }, ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_customer: Option<domain::Customer> = self .find_optional_resource( key_store, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), ) .await?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == pii::REDACTED) ...` match customer.name { Some(ref name) if name.peek() == pii::REDACTED => { Err(StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; self.find_optional_resource( key_store, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_customer: Option<domain::Customer> = self .find_optional_resource( key_store, customers::Customer::find_optional_by_merchant_id_merchant_reference_id( &conn, customer_id, merchant_id, ), ) .await?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == pii::REDACTED) ...` match customer.name { Some(ref name) if name.peek() == pii::REDACTED => { Err(StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, _customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; self.call_database( key_store, customers::Customer::update_by_customer_id_merchant_id( &conn, customer_id, merchant_id.clone(), customer_update.into(), ), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let customer: domain::Customer = self .call_database( key_store, customers::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), ) .await?; match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(customer), } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let customer: domain::Customer = self .call_database( key_store, customers::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ), ) .await?; match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(customer), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); self.find_resources( key_store, customers::Customer::list_customers_by_merchant_id_and_constraints( &conn, merchant_id, customer_list_constraints, ), ) .await } #[instrument(skip_all)] async fn list_customers_by_merchant_id_with_count( &self, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> { let conn = pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); let customers_constraints = diesel_models::query::customers::CustomerListConstraints { limit: customer_list_constraints.limit, offset: customer_list_constraints.offset, customer_id: customer_list_constraints.customer_id.clone(), time_range: customer_list_constraints.time_range, }; let customers = self .find_resources( key_store, customers::Customer::list_customers_by_merchant_id_and_constraints( &conn, merchant_id, customers_constraints, ), ) .await?; let total_count = customers::Customer::get_customer_count_by_merchant_id_and_constraints( &conn, merchant_id, customer_list_constraints, ) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })?; Ok((customers, total_count)) } #[instrument(skip_all)] async fn insert_customer( &self, customer_data: domain::Customer, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let customer_new = customer_data .construct_new() .await .change_context(StorageError::EncryptionError)?; self.call_database(key_store, customer_new.insert(&conn)) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_connection_write(self).await?; customers::Customer::delete_by_customer_id_merchant_id(&conn, customer_id, merchant_id) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, id: &id_type::GlobalCustomerId, _customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; self.call_database( key_store, customers::Customer::update_by_id(&conn, id.clone(), customer_update.into()), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, id: &id_type::GlobalCustomerId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let customer: domain::Customer = self .call_database(key_store, customers::Customer::find_by_global_id(&conn, id)) .await?; match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(customer), } } } #[async_trait::async_trait] impl domain::CustomerInterface for MockDb { type Error = StorageError; #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let customers = self.customers.lock().await; self.find_resource(key_store, customers, |customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .await } #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let customers = self.customers.lock().await; self.find_resource(key_store, customers, |customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .await } #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { todo!() } async fn list_customers_by_merchant_id( &self, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, StorageError> { let customers = self.customers.lock().await; let customers = try_join_all( customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .take(usize::from(constraints.limit)) .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0)) .map(|customer| async { customer .to_owned() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; Ok(customers) } async fn list_customers_by_merchant_id_with_count( &self, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> { let customers = self.customers.lock().await; let customers_list = try_join_all( customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .take(usize::from(constraints.limit)) .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0)) .map(|customer| async { customer .to_owned() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; let total_count = customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .count(); Ok((customers_list, total_count)) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, _customer_id: id_type::CustomerId, _merchant_id: id_type::MerchantId, _customer: domain::Customer, _customer_update: domain::CustomerUpdate, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_customer_by_customer_id_merchant_id( &self, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb`
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/platform_wrapper.rs
crates/storage_impl/src/platform_wrapper.rs
/// Platform wrapper for database operations /// /// Purpose: Prevent mixing Provider and Processor credentials when making DB calls. /// /// Use wrappers when: /// - You have Platform and need DB calls /// - Multiple credentials needed (key_store, merchant_id, storage_scheme) /// /// Direct DB calls are OK when no wrapper is needed: /// - Function already has Provider or Processor directly /// - All credentials are bundled in the context /// - Working with a deprecated module that still uses Processor /// /// Never mix Provider and Processor credentials or pass Platform to wrappers. /// Extract the specific context (Provider/Processor) and pass that instead. /// // TODO: Remove wrappers and migrate to DB interface with typed parameters (ProviderMerchantId, ProcessorMerchantId, etc.) once the platform stabilizes pub mod business_profile; pub mod payment_attempt; pub mod payment_intent;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/cards_info.rs
crates/storage_impl/src/cards_info.rs
pub use diesel_models::{CardInfo, UpdateCardInfo}; use error_stack::report; use hyperswitch_domain_models::cards_info::CardsInfoInterface; use router_env::{instrument, tracing}; use crate::{ errors::StorageError, kv_router_store::KVRouterStore, redis::kv_store::KvStorePartition, utils::{pg_connection_read, pg_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, }; impl KvStorePartition for CardInfo {} #[async_trait::async_trait] impl<T: DatabaseStore> CardsInfoInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { let conn = pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(StorageError::from(error))) } } #[async_trait::async_trait] impl<T: DatabaseStore> CardsInfoInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { let conn = pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(StorageError::from(error))) } } #[async_trait::async_trait] impl CardsInfoInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { Ok(self .cards_info .lock() .await .iter() .find(|ci| ci.card_iin == card_iin) .cloned()) } async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, StorageError> { Err(StorageError::MockDbError)? } async fn update_card_info( &self, _card_iin: String, _data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { Err(StorageError::MockDbError)? } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/merchant_account.rs
crates/storage_impl/src/merchant_account.rs
#[cfg(feature = "olap")] use std::collections::HashMap; use common_utils::ext_traits::AsyncExt; use diesel_models::merchant_account as storage; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, master_key::MasterKeyInterface, merchant_account::{self as domain, MerchantAccountInterface}, merchant_key_store::{MerchantKeyStore, MerchantKeyStoreInterface}, }; use masking::PeekInterface; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::{ cache, cache::{CacheKind, ACCOUNTS_CACHE}, }; #[cfg(feature = "accounts_cache")] use crate::RedisConnInterface; use crate::{ kv_router_store, store::MerchantAccountUpdateInternal, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantAccountInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant( &self, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .insert_merchant(merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .find_merchant_account_by_merchant_id(merchant_id, merchant_key_store) .await } #[instrument(skip_all)] async fn update_merchant( &self, this: domain::MerchantAccount, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .update_merchant(this, merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .update_specific_fields_in_merchant(merchant_id, merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { self.router_store .find_merchant_account_by_publishable_key(publishable_key) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { self.router_store .list_merchant_accounts_by_organization_id(organization_id) .await } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { self.router_store .list_multiple_merchant_accounts(merchant_ids) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { self.router_store .list_merchant_and_org_ids(limit, offset) .await } async fn update_all_merchant_account( &self, merchant_account: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { self.router_store .update_all_merchant_account(merchant_account) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant( &self, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; merchant_account .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) }; let state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert( state, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, merchant_id.get_string_repr(), fetch_func, &ACCOUNTS_CACHE, ) .await? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } } #[instrument(skip_all)] async fn update_merchant( &self, this: domain::MerchantAccount, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; let updated_merchant_account = Conversion::convert(this) .await .change_context(StorageError::EncryptionError)? .update(&conn, merchant_account.into()) .await .map_err(|error| report!(StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields( &conn, merchant_id, merchant_account.into(), ) .await .map_err(|error| report!(StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { let fetch_by_pub_key_func = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key) .await .map_err(|error| report!(StorageError::from(error))) }; let merchant_account; #[cfg(not(feature = "accounts_cache"))] { merchant_account = fetch_by_pub_key_func().await?; } #[cfg(feature = "accounts_cache")] { merchant_account = cache::get_or_populate_in_memory( self, publishable_key, fetch_by_pub_key_func, &ACCOUNTS_CACHE, ) .await?; } let key_store = self .get_merchant_key_store_by_merchant_id( merchant_account.get_id(), &self.master_key().peek().to_vec().into(), ) .await?; let domain_merchant_account = merchant_account .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok((domain_merchant_account, key_store)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { use futures::future::try_join_all; let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_by_organization_id(&conn, organization_id) .await .map_err(|error| report!(StorageError::from(error)))?; let db_master_key = self.master_key().peek().to_vec().into(); let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( merchant_account.get_id(), &db_master_key, ) })) .await?; let merchant_accounts = try_join_all( encrypted_merchant_accounts .into_iter() .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; Ok(merchant_accounts) } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_accounts_connection_write(self).await?; let is_deleted_func = || async { storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) }; let is_deleted; #[cfg(not(feature = "accounts_cache"))] { is_deleted = is_deleted_func().await?; } #[cfg(feature = "accounts_cache")] { let merchant_account = storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error)))?; is_deleted = is_deleted_func().await?; publish_and_redact_merchant_account_cache(self, &merchant_account).await?; } Ok(is_deleted) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids) .await .map_err(|error| report!(StorageError::from(error)))?; let db_master_key = self.master_key().peek().to_vec().into(); let merchant_key_stores = self .list_multiple_key_stores( encrypted_merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id()) .cloned() .collect(), &db_master_key, ) .await?; let key_stores_by_id: HashMap<_, _> = merchant_key_stores .iter() .map(|key_store| (key_store.merchant_id.to_owned(), key_store)) .collect(); let merchant_accounts = futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map( |merchant_account| async { let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or( StorageError::ValueNotFound(format!( "merchant_key_store with merchant_id = {:?}", merchant_account.get_id() )), )?; merchant_account .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }, )) .await?; Ok(merchant_accounts) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset) .await .map_err(|error| report!(StorageError::from(error)))?; let merchant_and_org_ids = encrypted_merchant_accounts .into_iter() .map(|merchant_account| { let merchant_id = merchant_account.get_id().clone(); let org_id = merchant_account.organization_id; (merchant_id, org_id) }) .collect(); Ok(merchant_and_org_ids) } async fn update_all_merchant_account( &self, merchant_account: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { let conn = pg_accounts_connection_read(self).await?; let db_func = || async { storage::MerchantAccount::update_all_merchant_accounts( &conn, MerchantAccountUpdateInternal::from(merchant_account), ) .await .map_err(|error| report!(StorageError::from(error))) }; let total; #[cfg(not(feature = "accounts_cache"))] { let ma = db_func().await?; total = ma.len(); } #[cfg(feature = "accounts_cache")] { let ma = db_func().await?; publish_and_redact_all_merchant_account_cache(self, &ma).await?; total = ma.len(); } Ok(total) } } #[async_trait::async_trait] impl MerchantAccountInterface for MockDb { type Error = StorageError; #[allow(clippy::panic)] async fn insert_merchant( &self, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let mut accounts = self.merchant_accounts.lock().await; let account = Conversion::convert(merchant_account) .await .change_context(StorageError::EncryptionError)?; accounts.push(account.clone()); account .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let accounts = self.merchant_accounts.lock().await; accounts .iter() .find(|account| account.get_id() == merchant_id) .cloned() .ok_or(StorageError::ValueNotFound(format!( "Merchant ID: {merchant_id:?} not found", )))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } async fn update_merchant( &self, merchant_account: domain::MerchantAccount, merchant_account_update: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let merchant_id = merchant_account.get_id().to_owned(); let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_account.get_id()) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset( Conversion::convert(merchant_account) .await .change_context(StorageError::EncryptionError)?, ); *account = update.clone(); update .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",)) .into(), ) } async fn update_specific_fields_in_merchant( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_account_update: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_id) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset(account.clone()); *account = update.clone(); update .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",)) .into(), ) } async fn find_merchant_account_by_publishable_key( &self, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { let accounts = self.merchant_accounts.lock().await; let account = accounts .iter() .find(|account| { account .publishable_key .as_ref() .is_some_and(|key| key == publishable_key) }) .ok_or(StorageError::ValueNotFound(format!( "Publishable Key: {publishable_key} not found", )))?; let key_store = self .get_merchant_key_store_by_merchant_id( account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let merchant_account = account .clone() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok((merchant_account, key_store)) } async fn update_all_merchant_account( &self, merchant_account_update: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { let mut accounts = self.merchant_accounts.lock().await; Ok(accounts.iter_mut().fold(0, |acc, account| { let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone()) .apply_changeset(account.clone()); *account = update; acc + 1 })) } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts.retain(|x| x.get_id() != merchant_id); Ok(true) } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| account.organization_id == *organization_id) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key.key.get_inner(), key.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| merchant_ids.contains(account.get_id())) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key.key.get_inner(), key.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { let accounts = self.merchant_accounts.lock().await; let limit = limit.try_into().unwrap_or(accounts.len()); let offset = offset.unwrap_or(0).try_into().unwrap_or(0); let merchant_and_org_ids = accounts .iter() .skip(offset) .take(limit) .map(|account| (account.get_id().clone(), account.organization_id.clone())) .collect::<Vec<_>>(); Ok(merchant_and_org_ids) } } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_merchant_account_cache( store: &(dyn RedisConnInterface + Send + Sync), merchant_account: &storage::MerchantAccount, ) -> CustomResult<(), StorageError> { let publishable_key = merchant_account .publishable_key .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); #[cfg(feature = "v1")] let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( "cgraph_{}_{}", merchant_account.get_id().get_string_repr(), profile_id.get_string_repr(), ) .into(), ) }); // TODO: we will not have default profile in v2 #[cfg(feature = "v2")] let cgraph_key = None; let mut cache_keys = vec![CacheKind::Accounts( merchant_account.get_id().get_string_repr().into(), )]; cache_keys.extend(publishable_key.into_iter()); cache_keys.extend(cgraph_key.into_iter()); cache::redact_from_redis_and_publish(store, cache_keys).await?; Ok(()) } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_all_merchant_account_cache( cache: &(dyn RedisConnInterface + Send + Sync), merchant_accounts: &[storage::MerchantAccount], ) -> CustomResult<(), StorageError> { let merchant_ids = merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string()); let publishable_keys = merchant_accounts .iter() .filter_map(|m| m.publishable_key.clone()); let cache_keys: Vec<CacheKind<'_>> = merchant_ids .chain(publishable_keys) .map(|s| CacheKind::Accounts(s.into())) .collect(); cache::redact_from_redis_and_publish(cache, cache_keys).await?; Ok(()) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/connection.rs
crates/storage_impl/src/connection.rs
use bb8::PooledConnection; use common_utils::errors; use diesel::PgConnection; use error_stack::ResultExt; 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( redis: &redis_interface::RedisSettings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(redis) .await .expect("Failed to create Redis Connection Pool") } pub async fn pg_connection_read<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::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(crate::errors::StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::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(crate::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/storage_impl/src/database.rs
crates/storage_impl/src/database.rs
pub mod store;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/mock_db.rs
crates/storage_impl/src/mock_db.rs
use std::sync::Arc; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models as store; use error_stack::ResultExt; use futures::lock::{Mutex, MutexGuard}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; use redis_interface::RedisSettings; use crate::{errors::StorageError, redis::RedisStore}; pub mod payment_attempt; pub mod payment_intent; #[cfg(feature = "payouts")] pub mod payout_attempt; #[cfg(feature = "payouts")] pub mod payouts; pub mod redis_conn; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; #[derive(Clone)] pub struct MockDb { pub addresses: Arc<Mutex<Vec<store::Address>>>, pub configs: Arc<Mutex<Vec<store::Config>>>, pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>, pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>, pub payment_attempts: Arc<Mutex<Vec<PaymentAttempt>>>, pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>, pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>, pub customers: Arc<Mutex<Vec<store::Customer>>>, pub refunds: Arc<Mutex<Vec<store::Refund>>>, pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>, pub redis: Arc<RedisStore>, pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>, pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>, pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>, pub events: Arc<Mutex<Vec<store::Event>>>, pub disputes: Arc<Mutex<Vec<store::Dispute>>>, pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>, pub mandates: Arc<Mutex<Vec<store::Mandate>>>, pub captures: Arc<Mutex<Vec<store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>, #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>, pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, pub users: Arc<Mutex<Vec<store::user::User>>>, pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, #[cfg(feature = "payouts")] pub payout_attempt: Arc<Mutex<Vec<store::payout_attempt::PayoutAttempt>>>, #[cfg(feature = "payouts")] pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>, pub authentications: Arc<Mutex<Vec<hyperswitch_domain_models::authentication::Authentication>>>, pub roles: Arc<Mutex<Vec<store::role::Role>>>, pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>, pub user_authentication_methods: Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>, pub hyperswitch_ai_interactions: Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>, pub key_manager_state: Option<KeyManagerState>, } impl MockDb { pub fn get_keymanager_state(&self) -> Result<&KeyManagerState, StorageError> { self.key_manager_state .as_ref() .ok_or(StorageError::DecryptionError) } pub async fn new( redis: &RedisSettings, key_manager_state: KeyManagerState, ) -> error_stack::Result<Self, StorageError> { Ok(Self { addresses: Default::default(), configs: Default::default(), merchant_accounts: Default::default(), merchant_connector_accounts: Default::default(), payment_attempts: Default::default(), payment_intents: Default::default(), payment_methods: Default::default(), customers: Default::default(), refunds: Default::default(), processes: Default::default(), redis: Arc::new( RedisStore::new(redis) .await .change_context(StorageError::InitializationError)?, ), api_keys: Default::default(), ephemeral_keys: Default::default(), cards_info: Default::default(), events: Default::default(), disputes: Default::default(), lockers: Default::default(), mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), #[cfg(all(feature = "v2", feature = "tokenization_v2"))] tokenizations: Default::default(), business_profiles: Default::default(), reverse_lookups: Default::default(), payment_link: Default::default(), organizations: Default::default(), users: Default::default(), user_roles: Default::default(), authorizations: Default::default(), dashboard_metadata: Default::default(), #[cfg(feature = "payouts")] payout_attempt: Default::default(), #[cfg(feature = "payouts")] payouts: Default::default(), authentications: Default::default(), roles: Default::default(), user_key_store: Default::default(), user_authentication_methods: Default::default(), themes: Default::default(), hyperswitch_ai_interactions: Default::default(), key_manager_state: Some(key_manager_state), }) } /// Returns an option of the resource if it exists pub async fn find_resource<D, R>( &self, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, ) -> CustomResult<Option<R>, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { let resource = resources.iter().find(filter_fn).cloned(); match resource { Some(res) => Ok(Some( res.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, )), None => Ok(None), } } /// Throws errors when the requested resource is not found pub async fn get_resource<D, R>( &self, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, error_message: String, ) -> CustomResult<R, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { match self.find_resource(key_store, resources, filter_fn).await? { Some(res) => Ok(res), None => Err(StorageError::ValueNotFound(error_message).into()), } } pub async fn get_resources<D, R>( &self, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, error_message: String, ) -> CustomResult<Vec<R>, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { let resources: Vec<_> = resources.iter().filter(filter_fn).cloned().collect(); if resources.is_empty() { Err(StorageError::ValueNotFound(error_message).into()) } else { let pm_futures = resources .into_iter() .map(|pm| async { pm.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .collect::<Vec<_>>(); let domain_resources = futures::future::try_join_all(pm_futures).await?; Ok(domain_resources) } } pub async fn update_resource<D, R>( &self, key_store: &MerchantKeyStore, mut resources: MutexGuard<'_, Vec<D>>, resource_updated: D, filter_fn: impl Fn(&&mut D) -> bool, error_message: String, ) -> CustomResult<R, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { if let Some(pm) = resources.iter_mut().find(filter_fn) { *pm = resource_updated.clone(); let result = resource_updated .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(result) } else { Err(StorageError::ValueNotFound(error_message).into()) } } pub fn master_key(&self) -> &[u8] { &[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, ] } } #[cfg(not(feature = "payouts"))] impl PayoutsInterface for MockDb {} #[cfg(not(feature = "payouts"))] impl PayoutAttemptInterface for MockDb {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/subscription.rs
crates/storage_impl/src/subscription.rs
use common_utils::errors::CustomResult; pub use diesel_models::subscription::Subscription; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, subscription::{ Subscription as DomainSubscription, SubscriptionInterface, SubscriptionUpdate as DomainSubscriptionUpdate, }, }; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, key_store: &MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { let sub_new = subscription_new .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database(key_store, sub_new.insert(&conn)).await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { let conn = connection::pg_connection_write(self).await?; self.call_database( key_store, Subscription::find_by_merchant_id_subscription_id(&conn, merchant_id, subscription_id), ) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { let sub_new = data .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database( key_store, Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, sub_new), ) .await } #[instrument(skip_all)] async fn list_by_merchant_id_profile_id( &self, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<DomainSubscription>, StorageError> { let conn = connection::pg_connection_write(self).await?; self.find_resources( key_store, Subscription::list_by_merchant_id_profile_id( &conn, merchant_id, profile_id, limit, offset, ), ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> SubscriptionInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, key_store: &MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .insert_subscription_entry(key_store, subscription_new) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .find_by_merchant_id_subscription_id(key_store, merchant_id, subscription_id) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .update_subscription_entry(key_store, merchant_id, subscription_id, data) .await } #[instrument(skip_all)] async fn list_by_merchant_id_profile_id( &self, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<DomainSubscription>, StorageError> { self.router_store .list_by_merchant_id_profile_id(key_store, merchant_id, profile_id, limit, offset) .await } } #[async_trait::async_trait] impl SubscriptionInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, _key_store: &MerchantKeyStore, _subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } async fn find_by_merchant_id_subscription_id( &self, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } async fn update_subscription_entry( &self, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, _data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } #[instrument(skip_all)] async fn list_by_merchant_id_profile_id( &self, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _profile_id: &common_utils::id_type::ProfileId, _limit: Option<i64>, _offset: Option<i64>, ) -> CustomResult<Vec<DomainSubscription>, StorageError> { Err(StorageError::MockDbError)? } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/invoice.rs
crates/storage_impl/src/invoice.rs
use common_utils::errors::CustomResult; pub use diesel_models::invoice::Invoice; use error_stack::{report, ResultExt}; pub use hyperswitch_domain_models::{ behaviour::Conversion, invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate}, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, key_store: &MerchantKeyStore, invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, StorageError> { let inv_new = invoice_new .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database(key_store, inv_new.insert(&conn)).await } #[instrument(skip_all)] async fn find_invoice_by_invoice_id( &self, key_store: &MerchantKeyStore, invoice_id: String, ) -> CustomResult<DomainInvoice, StorageError> { let conn = connection::pg_connection_read(self).await?; self.call_database( key_store, Invoice::find_invoice_by_id_invoice_id(&conn, invoice_id), ) .await } #[instrument(skip_all)] async fn update_invoice_entry( &self, key_store: &MerchantKeyStore, invoice_id: String, data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, StorageError> { let inv_new = data .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database( key_store, Invoice::update_invoice_entry(&conn, invoice_id, inv_new), ) .await } #[instrument(skip_all)] async fn get_latest_invoice_for_subscription( &self, key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<DomainInvoice, StorageError> { let conn = connection::pg_connection_write(self).await?; let invoices: Vec<DomainInvoice> = self .find_resources( key_store, Invoice::list_invoices_by_subscription_id( &conn, subscription_id.clone(), Some(1), None, false, ), ) .await?; invoices .last() .cloned() .ok_or(report!(StorageError::ValueNotFound(format!( "Invoice not found for subscription_id: {}", subscription_id )))) } #[instrument(skip_all)] async fn find_invoice_by_subscription_id_connector_invoice_id( &self, key_store: &MerchantKeyStore, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, StorageError> { let conn = connection::pg_connection_read(self).await?; self.find_optional_resource( key_store, Invoice::get_invoice_by_subscription_id_connector_invoice_id( &conn, subscription_id, connector_invoice_id, ), ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> InvoiceInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, key_store: &MerchantKeyStore, invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .insert_invoice_entry(key_store, invoice_new) .await } #[instrument(skip_all)] async fn find_invoice_by_invoice_id( &self, key_store: &MerchantKeyStore, invoice_id: String, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .find_invoice_by_invoice_id(key_store, invoice_id) .await } #[instrument(skip_all)] async fn update_invoice_entry( &self, key_store: &MerchantKeyStore, invoice_id: String, data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .update_invoice_entry(key_store, invoice_id, data) .await } #[instrument(skip_all)] async fn get_latest_invoice_for_subscription( &self, key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .get_latest_invoice_for_subscription(key_store, subscription_id) .await } #[instrument(skip_all)] async fn find_invoice_by_subscription_id_connector_invoice_id( &self, key_store: &MerchantKeyStore, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, StorageError> { self.router_store .find_invoice_by_subscription_id_connector_invoice_id( key_store, subscription_id, connector_invoice_id, ) .await } } #[async_trait::async_trait] impl InvoiceInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, _key_store: &MerchantKeyStore, _invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn find_invoice_by_invoice_id( &self, _key_store: &MerchantKeyStore, _invoice_id: String, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn update_invoice_entry( &self, _key_store: &MerchantKeyStore, _invoice_id: String, _data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn get_latest_invoice_for_subscription( &self, _key_store: &MerchantKeyStore, _subscription_id: String, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn find_invoice_by_subscription_id_connector_invoice_id( &self, _key_store: &MerchantKeyStore, _subscription_id: String, _connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, StorageError> { Err(StorageError::MockDbError)? } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/merchant_connector_account.rs
crates/storage_impl/src/merchant_connector_account.rs
use async_bb8_diesel::AsyncConnection; use common_utils::{encryption::Encryption, ext_traits::AsyncExt}; use diesel_models::merchant_connector_account as storage; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_connector_account::{self as domain, MerchantConnectorAccountInterface}, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::cache; use crate::{ kv_router_store, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantConnectorAccountInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_connector_label( merchant_id, connector_label, key_store, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_profile_id_connector_name( profile_id, connector_name, key_store, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_connector_name( merchant_id, connector_name, key_store, ) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, key_store, ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_id(id, key_store) .await } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .insert_merchant_connector_account(t, key_store) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .list_enabled_connector_accounts_by_profile_id(profile_id, key_store, connector_type) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( merchant_id, get_disabled, key_store, ) .await } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .list_connector_account_by_profile_id(profile_id, key_store) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error> { self.router_store .update_multiple_merchant_connector_accounts(merchant_connector_accounts) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .update_merchant_connector_account(this, merchant_connector_account, key_store) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .update_merchant_connector_account(this, merchant_connector_account, key_store) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_connector_account_by_id(id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector( &conn, merchant_id, connector_label, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), merchant_id.clone().into(), ) .await .change_context(Self::Error::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", merchant_id.get_string_repr(), connector_label), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_profile_id_connector_name( &conn, profile_id, connector_name, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", profile_id.get_string_repr(), connector_name), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector_name( &conn, merchant_id, connector_name, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!( "{}_{}", merchant_id.get_string_repr(), merchant_connector_id.get_string_repr() ), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone(), ) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, id.get_string_repr(), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let conn = pg_accounts_connection_write(self).await?; t.construct_new() .await .change_context(Self::Error::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_enabled_by_profile_id( &conn, profile_id, connector_type, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> { let conn = pg_accounts_connection_read(self).await?; let merchant_connector_account_vec = storage::MerchantConnectorAccount::find_by_merchant_id( &conn, merchant_id, get_disabled, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await?; Ok(domain::MerchantConnectorAccounts::new( merchant_connector_account_vec, )) } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error> { let conn = pg_accounts_connection_write(self).await?; async fn update_call( connection: &diesel_models::PgPooledConn, (merchant_connector_account, mca_update): ( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, ), ) -> Result<(), error_stack::Report<StorageError>> { Conversion::convert(merchant_connector_account) .await .change_context(StorageError::EncryptionError)? .update(connection, mca_update) .await .map_err(|error| report!(StorageError::from(error)))?; Ok(()) } conn.transaction_async(|connection_pool| async move { for (merchant_connector_account, update_merchant_connector_account) in merchant_connector_accounts { #[cfg(feature = "v1")] let _connector_name = merchant_connector_account.connector_name.clone(); #[cfg(feature = "v2")] let _connector_name = merchant_connector_account.connector_name.to_string(); let _profile_id = merchant_connector_account.profile_id.clone(); let _merchant_id = merchant_connector_account.merchant_id.clone(); let _merchant_connector_id = merchant_connector_account.get_id().clone(); let update = update_call( &connection_pool, ( merchant_connector_account, update_merchant_connector_account, ), ); #[cfg(feature = "accounts_cache")] // Redact all caches as any of might be used because of backwards compatibility Box::pin(cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], || update, )) .await .map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); Self::Error::DatabaseConnectionError })?; #[cfg(not(feature = "accounts_cache"))] { update.await.map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); Self::Error::DatabaseConnectionError })?; } } Ok::<_, Self::Error>(()) }) .await?; Ok(()) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let _connector_name = this.connector_name.clone(); let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.merchant_connector_id.clone(); let update_call = || async { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(Self::Error::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr(), ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let _connector_name = this.connector_name; let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.get_id().clone(); let update_call = || async { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(Self::Error::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(Self::Error::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( _merchant_connector_id.get_string_repr().to_string().into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v1")]
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payment_method.rs
crates/storage_impl/src/payment_method.rs
pub use diesel_models::payment_method::PaymentMethod; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentMethod {} #[cfg(feature = "v1")] use std::collections::HashSet; use common_enums::enums::MerchantStorageScheme; use common_utils::{errors::CustomResult, id_type}; #[cfg(feature = "v1")] use diesel_models::kv; use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::behaviour::ReverseConversion; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface}, }; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ diesel_error_to_data_error, errors, kv_router_store::{FindResourceBy, KVRouterStore}, utils::{pg_connection_read, pg_connection_write}, DatabaseStore, RouterStore, }; #[cfg(feature = "v1")] use crate::{ kv_router_store::{FilterResourceParams, InsertResourceParams, UpdateResourceParams}, redis::kv_store::{Op, PartitionKey}, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method( &self, key_store: &MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( key_store, storage_scheme, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), FindResourceBy::LookupId(format!("payment_method_{payment_method_id}")), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method( &self, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( key_store, storage_scheme, PaymentMethod::find_by_id(&conn, payment_method_id), FindResourceBy::LookupId(format!( "payment_method_{}", payment_method_id.get_string_repr() )), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, key_store: &MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( key_store, storage_scheme, PaymentMethod::find_by_locker_id(&conn, locker_id), FindResourceBy::LookupId(format!("payment_method_locker_{locker_id}")), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_methods_by_merchant_id_payment_method_ids( &self, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_ids: &[String], storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_methods_by_merchant_id_payment_method_ids( key_store, merchant_id, payment_method_ids, storage_scheme, ) .await } // not supported in kv #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_customer_id_merchant_id_status( customer_id, merchant_id, status, ) .await } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_merchant_id_status(merchant_id, status) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .insert_payment_method(key_store, payment_method, storage_scheme) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; let mut payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; payment_method_new.update_storage_scheme(storage_scheme); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &payment_method_new.merchant_id.clone(), customer_id: &payment_method_new.customer_id.clone(), }; let identifier = format!("payment_method_id_{}", payment_method_new.get_id()); let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id()); let mut reverse_lookups = vec![lookup_id1]; if let Some(locker_id) = &payment_method_new.locker_id { reverse_lookups.push(format!("payment_method_locker_{locker_id}")) } let payment_method = (&payment_method_new.clone()).into(); self.insert_resource( key_store, storage_scheme, payment_method_new.clone().insert(&conn), payment_method, InsertResourceParams { insertable: kv::Insertable::PaymentMethod(Box::new(payment_method_new.clone())), reverse_lookups, key, identifier, resource_type: "payment_method", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let merchant_id = payment_method.merchant_id.clone(); let customer_id = payment_method.customer_id.clone(); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let conn = pg_connection_write(self).await?; let field = format!("payment_method_id_{}", payment_method.get_id().clone()); let p_update: PaymentMethodUpdateInternal = payment_method_update.convert_to_payment_method_update(storage_scheme); let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone()); self.update_resource( key_store, storage_scheme, payment_method .clone() .update_with_payment_method_id(&conn, p_update.clone()), updated_payment_method, UpdateResourceParams { updateable: kv::Updateable::PaymentMethodUpdate(Box::new( kv::PaymentMethodUpdateMems { orig: payment_method.clone(), update_data: p_update.clone(), }, )), operation: Op::Update( key.clone(), &field, payment_method.clone().updated_by.as_deref(), ), }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .update_payment_method( key_store, payment_method, payment_method_update, storage_scheme, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_customer_id_merchant_id_list( key_store, customer_id, merchant_id, limit, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_list_by_global_customer_id(key_store, customer_id, limit) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.filter_resources( key_store, storage_scheme, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), |pm| pm.status == status, FilterResourceParams { key: PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, pattern: "payment_method_id_*", limit, }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_global_customer_id_merchant_id_status( key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method_by_merchant_id_payment_method_id( key_store, merchant_id, payment_method_id, ) .await } // Soft delete, Check if KV stuff is needed here #[cfg(feature = "v2")] async fn delete_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method(key_store, payment_method) .await } // Check if KV stuff is needed here #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .find_payment_method_by_fingerprint_id(key_store, fingerprint_id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_method( &self, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( key_store, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), ) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( key_store, PaymentMethod::find_by_id(&conn, payment_method_id), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( key_store, PaymentMethod::find_by_locker_id(&conn, locker_id), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_methods_by_merchant_id_payment_method_ids( &self, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_ids: &[String], _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( key_store, PaymentMethod::find_by_merchant_id_payment_method_ids( &conn, merchant_id, payment_method_ids, Some(200), ), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, ) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn insert_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database(key_store, payment_method_new.insert(&conn)) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( key_store, payment_method.update_with_payment_method_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( key_store, PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit), ) .await } // Need to fix this once we move to payment method for customer #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_list_by_global_customer_id( &self, key_store: &MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( key_store, PaymentMethod::find_by_global_customer_id(&conn, id, limit), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( key_store, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( key_store, PaymentMethod::find_by_global_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; self.call_database( key_store, PaymentMethod::delete_by_merchant_id_payment_method_id( &conn, merchant_id, payment_method_id, ), ) .await } #[cfg(feature = "v2")] async fn delete_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), last_modified_by: None, }; self.call_database( key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( key_store, PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id), ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for MockDb { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn find_payment_method( &self, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_locker_id( &self, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( key_store, payment_methods, |pm| pm.locker_id == Some(locker_id.to_string()), "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn find_payment_methods_by_merchant_id_payment_method_ids( &self, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_ids: &[String], _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { if payment_method_ids.is_empty() { return Ok(Vec::new()); } let ids: HashSet<_> = payment_method_ids.iter().cloned().collect(); let payment_methods = self.payment_methods.lock().await; self.get_resources( key_store, payment_methods, |pm| pm.merchant_id == *merchant_id && ids.contains(pm.get_id()), "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| pm.merchant_id == *merchant_id && pm.status == status) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn insert_payment_method( &self, _key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; let pm = Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::DecryptionError)?; payment_methods.push(pm); Ok(payment_method) } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resources( key_store, payment_methods, |pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id, "cannot find payment method".to_string(), ) .await } // Need to fix this once we complete v2 payment method #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, _key_store: &MerchantKeyStore, _id: &id_type::GlobalCustomerId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { todo!() } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_status( &self, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resources( key_store, payment_methods, |pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let find_pm_by = |pm: &&PaymentMethod| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }; let error_message = "cannot find payment method".to_string(); self.get_resources(key_store, payment_methods, find_pm_by, error_message) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; match payment_methods .iter() .position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id) { Some(index) => { let deleted_payment_method = payment_methods.remove(index); Ok(deleted_payment_method .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?) } None => Err(errors::StorageError::ValueNotFound( "cannot find payment method to delete".to_string(), ) .into()), } } async fn update_payment_method( &self, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme,
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payouts.rs
crates/storage_impl/src/payouts.rs
pub mod payout_attempt; #[allow(clippy::module_inception)] pub mod payouts; use diesel_models::{payout_attempt::PayoutAttempt, payouts::Payouts}; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Payouts {} impl KvStorePartition for PayoutAttempt {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/utils.rs
crates/storage_impl/src/utils.rs
use bb8::PooledConnection; use diesel::PgConnection; use error_stack::ResultExt; use crate::{ errors::{RedisErrorExt, StorageError}, metrics, DatabaseStore, }; pub async fn pg_connection_read<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_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(StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_read<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_accounts_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_write<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>( redis_fut: RFut, database_call_closure: F, ) -> error_stack::Result<T, StorageError> where F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<T, StorageError>>, { let redis_output = redis_fut.await; match redis_output { Ok(output) => Ok(output), Err(redis_error) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call_closure().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } } use std::collections::HashSet; use crate::UniqueConstraints; fn union_vec<T>(mut kv_rows: Vec<T>, sql_rows: Vec<T>) -> Vec<T> where T: UniqueConstraints, { let mut kv_unique_keys = HashSet::new(); kv_rows.iter().for_each(|v| { kv_unique_keys.insert(v.unique_constraints().concat()); }); sql_rows.into_iter().for_each(|v| { let unique_key = v.unique_constraints().concat(); if !kv_unique_keys.contains(&unique_key) { kv_rows.push(v); } }); kv_rows } pub async fn find_all_combined_kv_database<F, RFut, DFut, T>( redis_fut: RFut, database_call: F, limit: Option<i64>, ) -> error_stack::Result<Vec<T>, StorageError> where T: UniqueConstraints, F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<Vec<T>, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<Vec<T>, StorageError>>, { let trunc = |v: &mut Vec<_>| { if let Some(l) = limit.and_then(|v| TryInto::try_into(v).ok()) { v.truncate(l); } }; let limit_satisfies = |len: usize, limit: i64| { TryInto::try_into(limit) .ok() .is_none_or(|val: usize| len >= val) }; let redis_output = redis_fut.await; match (redis_output, limit) { (Ok(mut kv_rows), Some(lim)) if limit_satisfies(kv_rows.len(), lim) => { trunc(&mut kv_rows); Ok(kv_rows) } (Ok(kv_rows), _) => database_call().await.map(|db_rows| { let mut res = union_vec(kv_rows, db_rows); trunc(&mut res); res }), (Err(redis_error), _) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/lookup.rs
crates/storage_impl/src/lookup.rs
use common_utils::errors::CustomResult; use diesel_models::{ enums as storage_enums, kv, reverse_lookup::{ ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew, }, }; use error_stack::ResultExt; use redis_interface::SetnxReply; use crate::{ diesel_error_to_data_error, errors::{self, RedisErrorExt}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, try_redis_get_else_try_database_get}, DatabaseStore, RouterStore, }; #[async_trait::async_trait] pub trait ReverseLookupInterface { async fn insert_reverse_lookup( &self, _new: DieselReverseLookupNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError>; async fn get_lookup_by_lookup_id( &self, _id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError>; } #[async_trait::async_trait] impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> { async fn insert_reverse_lookup( &self, new: DieselReverseLookupNew, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let conn = self .get_master_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; new.insert(&conn).await.map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } async fn get_lookup_by_lookup_id( &self, id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let conn = utils::pg_connection_read(self).await?; DieselReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } #[async_trait::async_trait] impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> { async fn insert_reverse_lookup( &self, new: DieselReverseLookupNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { storage_enums::MerchantStorageScheme::PostgresOnly => { self.router_store .insert_reverse_lookup(new, storage_scheme) .await } storage_enums::MerchantStorageScheme::RedisKv => { let created_rev_lookup = DieselReverseLookup { lookup_id: new.lookup_id.clone(), sk_id: new.sk_id.clone(), pk_id: new.pk_id.clone(), source: new.source.clone(), updated_by: storage_scheme.to_string(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id), }, )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() { Ok(SetnxReply::KeySet) => Ok(created_rev_lookup), Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "reverse_lookup", key: Some(created_rev_lookup.lookup_id.clone()), } .into()), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let database_call = || async { self.router_store .get_lookup_by_lookup_id(id, storage_scheme) .await }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await, storage_enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { Box::pin(kv_wrapper( self, KvOperation::<DieselReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, )) .await? .try_into_get() }; Box::pin(try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/business_profile.rs
crates/storage_impl/src/business_profile.rs
use common_utils::ext_traits::AsyncExt; use diesel_models::business_profile::{self, ProfileUpdateInternal}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, business_profile as domain, business_profile::ProfileInterface, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; use crate::{ kv_router_store, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> ProfileInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_business_profile( &self, merchant_key_store: &MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .insert_business_profile(merchant_key_store, business_profile) .await } #[instrument(skip_all)] async fn find_business_profile_by_profile_id( &self, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .find_business_profile_by_profile_id(merchant_key_store, profile_id) .await } async fn find_business_profile_by_merchant_id_profile_id( &self, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .find_business_profile_by_merchant_id_profile_id( merchant_key_store, merchant_id, profile_id, ) .await } #[instrument(skip_all)] async fn find_business_profile_by_profile_name_merchant_id( &self, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .find_business_profile_by_profile_name_merchant_id( merchant_key_store, profile_name, merchant_id, ) .await } #[instrument(skip_all)] async fn update_profile_by_profile_id( &self, merchant_key_store: &MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .update_profile_by_profile_id(merchant_key_store, current_state, profile_update) .await } #[instrument(skip_all)] async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_profile_by_profile_id_merchant_id(profile_id, merchant_id) .await } #[instrument(skip_all)] async fn list_profile_by_merchant_id( &self, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, StorageError> { self.router_store .list_profile_by_merchant_id(merchant_key_store, merchant_id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> ProfileInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_business_profile( &self, merchant_key_store: &MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_write(self).await?; business_profile .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_business_profile_by_profile_id( &self, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.call_database( merchant_key_store, business_profile::Profile::find_by_profile_id(&conn, profile_id), ) .await } async fn find_business_profile_by_merchant_id_profile_id( &self, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.call_database( merchant_key_store, business_profile::Profile::find_by_merchant_id_profile_id( &conn, merchant_id, profile_id, ), ) .await } #[instrument(skip_all)] async fn find_business_profile_by_profile_name_merchant_id( &self, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.call_database( merchant_key_store, business_profile::Profile::find_by_profile_name_merchant_id( &conn, profile_name, merchant_id, ), ) .await } #[instrument(skip_all)] async fn update_profile_by_profile_id( &self, merchant_key_store: &MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(current_state) .await .change_context(StorageError::EncryptionError)? .update_by_profile_id(&conn, ProfileUpdateInternal::from(profile_update)) .await .map_err(|error| report!(StorageError::from(error)))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_accounts_connection_write(self).await?; business_profile::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn list_profile_by_merchant_id( &self, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.find_resources( merchant_key_store, business_profile::Profile::list_profile_by_merchant_id(&conn, merchant_id), ) .await } } #[async_trait::async_trait] impl ProfileInterface for MockDb { type Error = StorageError; async fn insert_business_profile( &self, merchant_key_store: &MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, StorageError> { let stored_business_profile = Conversion::convert(business_profile) .await .change_context(StorageError::EncryptionError)?; self.business_profiles .lock() .await .push(stored_business_profile.clone()); stored_business_profile .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } async fn find_business_profile_by_profile_id( &self, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| business_profile.get_id() == profile_id) .cloned() .async_map(|business_profile| async { business_profile .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?}" )) .into(), ) } async fn find_business_profile_by_merchant_id_profile_id( &self, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| { business_profile.merchant_id == *merchant_id && business_profile.get_id() == profile_id }) .cloned() .async_map(|business_profile| async { business_profile .convert( self.get_keymanager_state().attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!( "No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}" )) .into(), ) } async fn update_profile_by_profile_id( &self, merchant_key_store: &MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, StorageError> { let profile_id = current_state.get_id().to_owned(); self.business_profiles .lock() .await .iter_mut() .find(|business_profile| business_profile.get_id() == current_state.get_id()) .async_map(|business_profile| async { let profile_updated = ProfileUpdateInternal::from(profile_update).apply_changeset( Conversion::convert(current_state) .await .change_context(StorageError::EncryptionError)?, ); *business_profile = profile_updated.clone(); profile_updated .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?}", )) .into(), ) } async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut business_profiles = self.business_profiles.lock().await; let index = business_profiles .iter() .position(|business_profile| { business_profile.get_id() == profile_id && business_profile.merchant_id == *merchant_id }) .ok_or::<StorageError>(StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?} and merchant_id = {merchant_id:?}" )))?; business_profiles.remove(index); Ok(true) } async fn list_profile_by_merchant_id( &self, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, StorageError> { let business_profiles = self .business_profiles .lock() .await .iter() .filter(|business_profile| business_profile.merchant_id == *merchant_id) .cloned() .collect::<Vec<_>>(); let mut domain_business_profiles = Vec::with_capacity(business_profiles.len()); for business_profile in business_profiles { let domain_profile = business_profile .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; domain_business_profiles.push(domain_profile); } Ok(domain_business_profiles) } async fn find_business_profile_by_profile_name_merchant_id( &self, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| { business_profile.profile_name == profile_name && business_profile.merchant_id == *merchant_id }) .cloned() .async_map(|business_profile| async { business_profile .convert( self.get_keymanager_state().attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!( "No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}" )) .into(), ) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/mandate.rs
crates/storage_impl/src/mandate.rs
use diesel_models::Mandate; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Mandate {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/metrics.rs
crates/storage_impl/src/metrics.rs
use router_env::{counter_metric, gauge_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // Metrics for KV counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER); counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER); counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER); counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER); counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER); // Metrics for In-memory cache gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER);
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/refund.rs
crates/storage_impl/src/refund.rs
use diesel_models::refund::Refund; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Refund {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/kv_router_store.rs
crates/storage_impl/src/kv_router_store.rs
use std::{fmt::Debug, sync::Arc}; use common_enums::enums::MerchantStorageScheme; use common_utils::{fallback_reverse_lookup_not_found, types::keymanager::KeyManagerState}; use diesel_models::{errors::DatabaseError, kv}; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::StrongSecret; use redis_interface::{errors::RedisError, types::HsetnxReply, RedisConnectionPool}; use router_env::logger; use serde::de; #[cfg(not(feature = "payouts"))] pub use crate::database::store::Store; pub use crate::{database::store::DatabaseStore, mock_db::MockDb}; use crate::{ database::store::PgPool, diesel_error_to_data_error, errors::{self, RedisErrorExt, StorageResult}, lookup::ReverseLookupInterface, metrics, redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, KvStorePartition, Op, PartitionKey, RedisConnInterface, }, utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get}, RouterStore, TenantConfig, UniqueConstraints, }; #[derive(Debug, Clone)] pub struct KVRouterStore<T: DatabaseStore> { pub router_store: RouterStore<T>, pub key_manager_state: Option<KeyManagerState>, drainer_stream_name: String, drainer_num_partitions: u8, pub ttl_for_kv: u32, pub request_id: Option<String>, pub soft_kill_mode: bool, } impl<T: DatabaseStore> KVRouterStore<T> { pub fn get_keymanager_state(&self) -> Result<&KeyManagerState, errors::StorageError> { self.key_manager_state .as_ref() .ok_or_else(|| errors::StorageError::DecryptionError) } } pub struct InsertResourceParams<'a> { pub insertable: kv::Insertable, pub reverse_lookups: Vec<String>, pub key: PartitionKey<'a>, // secondary key pub identifier: String, // type of resource Eg: "payment_attempt" pub resource_type: &'static str, } pub struct UpdateResourceParams<'a> { pub updateable: kv::Updateable, pub operation: Op<'a>, } pub struct FilterResourceParams<'a> { pub key: PartitionKey<'a>, pub pattern: &'static str, pub limit: Option<i64>, } pub enum FindResourceBy<'a> { Id(String, PartitionKey<'a>), LookupId(String), } pub trait DomainType: Debug + Sync + Conversion {} impl<T: Debug + Sync + Conversion> DomainType for T {} /// Storage model with all required capabilities for KV operations pub trait StorageModel<D: Conversion>: de::DeserializeOwned + serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync + Send + ReverseConversion<D> { } impl<T, D> StorageModel<D> for T where T: de::DeserializeOwned + serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync + Send + ReverseConversion<D>, D: DomainType, { } #[async_trait::async_trait] impl<T> DatabaseStore for KVRouterStore<T> where RouterStore<T>: DatabaseStore, T: DatabaseStore, { type Config = (RouterStore<T>, String, u8, u32, Option<bool>); async fn new( config: Self::Config, tenant_config: &dyn TenantConfig, _test_transaction: bool, key_manager_state: Option<KeyManagerState>, ) -> StorageResult<Self> { let (router_store, _, drainer_num_partitions, ttl_for_kv, soft_kill_mode) = config; let drainer_stream_name = format!("{}_{}", tenant_config.get_schema(), config.1); Ok(Self::from_store( router_store, drainer_stream_name, drainer_num_partitions, ttl_for_kv, soft_kill_mode, key_manager_state, )) } fn get_master_pool(&self) -> &PgPool { self.router_store.get_master_pool() } fn get_replica_pool(&self) -> &PgPool { self.router_store.get_replica_pool() } fn get_accounts_master_pool(&self) -> &PgPool { self.router_store.get_accounts_master_pool() } fn get_accounts_replica_pool(&self) -> &PgPool { self.router_store.get_accounts_replica_pool() } } impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> { fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> { self.router_store.get_redis_conn() } } impl<T: DatabaseStore> KVRouterStore<T> { pub fn from_store( store: RouterStore<T>, drainer_stream_name: String, drainer_num_partitions: u8, ttl_for_kv: u32, soft_kill: Option<bool>, key_manager_state: Option<KeyManagerState>, ) -> Self { let request_id = store.request_id.clone(); Self { router_store: store, drainer_stream_name, drainer_num_partitions, ttl_for_kv, request_id, soft_kill_mode: soft_kill.unwrap_or(false), key_manager_state, } } pub fn master_key(&self) -> &StrongSecret<Vec<u8>> { self.router_store.master_key() } pub fn get_drainer_stream_name(&self, shard_key: &str) -> String { format!("{{{}}}_{}", shard_key, self.drainer_stream_name) } pub async fn push_to_drainer_stream<R>( &self, redis_entry: kv::TypedSql, partition_key: PartitionKey<'_>, ) -> error_stack::Result<(), RedisError> where R: KvStorePartition, { let global_id = format!("{partition_key}"); let request_id = self.request_id.clone().unwrap_or_default(); let shard_key = R::shard_key(partition_key, self.drainer_num_partitions); let stream_name = self.get_drainer_stream_name(&shard_key); self.router_store .cache_store .redis_conn .stream_append_entry( &stream_name.into(), &redis_interface::RedisEntryId::AutoGeneratedID, redis_entry .to_field_value_pairs(request_id, global_id) .change_context(RedisError::JsonSerializationFailed)?, ) .await .map(|_| metrics::KV_PUSHED_TO_DRAINER.add(1, &[])) .inspect_err(|error| { metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(1, &[]); logger::error!(?error, "Failed to add entry in drainer stream"); }) .change_context(RedisError::StreamAppendFailed) } pub async fn find_resource_by_id<D, R, M>( &self, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, find_resource_db_fut: R, find_by: FindResourceBy<'_>, ) -> error_stack::Result<D, errors::StorageError> where D: DomainType, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send, { let database_call = || async { find_resource_db_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<T, M>( self, storage_scheme, Op::Find, )) .await; let res = || async { match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let (field, key) = match find_by { FindResourceBy::Id(field, key) => (field, key), FindResourceBy::LookupId(lookup_id) => { let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); ( lookup.clone().sk_id, PartitionKey::CombinationKey { combination: &lookup.clone().pk_id, }, ) } }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key)) .await? .try_into_hget() }, database_call, )) .await } } }; res() .await? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } pub async fn find_optional_resource_by_id<D, R, M>( &self, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, find_resource_db_fut: R, find_by: FindResourceBy<'_>, ) -> error_stack::Result<Option<D>, errors::StorageError> where D: DomainType, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<Option<M>, DatabaseError>> + Send, { let database_call = || async { find_resource_db_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<T, M>( self, storage_scheme, Op::Find, )) .await; let res = || async { match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let (field, key) = match find_by { FindResourceBy::Id(field, key) => (field, key), FindResourceBy::LookupId(lookup_id) => { let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); ( lookup.clone().sk_id, PartitionKey::CombinationKey { combination: &lookup.clone().pk_id, }, ) } }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key)) .await? .try_into_hget() .map(Some) }, database_call, )) .await } } }; match res().await? { Some(resource) => Ok(Some( resource .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, )), None => Ok(None), } } pub async fn insert_resource<D, R, M>( &self, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, create_resource_fut: R, resource_new: M, InsertResourceParams { insertable, reverse_lookups, key, identifier, resource_type, }: InsertResourceParams<'_>, ) -> error_stack::Result<D, errors::StorageError> where D: Debug + Sync + Conversion, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send, { let storage_scheme = Box::pin(decide_storage_scheme::<_, M>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => create_resource_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }), MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew { sk_id: identifier.clone(), pk_id: key_str.clone(), lookup_id: v, source: resource_type.to_string(), updated_by: storage_scheme.to_string(), }; let results = reverse_lookups .into_iter() .map(|v| self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme)); futures::future::try_join_all(results).await?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(insertable), }, }; match Box::pin(kv_wrapper::<M, _, _>( self, KvOperation::<M>::HSetNx(&identifier, &resource_new, redis_entry), key.clone(), )) .await .map_err(|err| err.to_redis_failed_response(&key.to_string()))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: resource_type, key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(resource_new), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } }? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } pub async fn update_resource<D, R, M>( &self, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, update_resource_fut: R, updated_resource: M, UpdateResourceParams { updateable, operation, }: UpdateResourceParams<'_>, ) -> error_stack::Result<D, errors::StorageError> where D: Debug + Sync + Conversion, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send, { match operation { Op::Update(key, field, updated_by) => { let storage_scheme = Box::pin(decide_storage_scheme::<_, M>( self, storage_scheme, Op::Update(key.clone(), field, updated_by), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { update_resource_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let redis_value = serde_json::to_string(&updated_resource) .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(updateable), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<M>::Hset((field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_resource) } } } _ => Err(errors::StorageError::KVError.into()), }? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } pub async fn filter_resources<D, R, M>( &self, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, filter_resource_db_fut: R, filter_fn: impl Fn(&M) -> bool, FilterResourceParams { key, pattern, limit, }: FilterResourceParams<'_>, ) -> error_stack::Result<Vec<D>, errors::StorageError> where D: Debug + Sync + Conversion, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<Vec<M>, DatabaseError>> + Send, { let db_call = || async { filter_resource_db_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) }; let resources = match storage_scheme { MerchantStorageScheme::PostgresOnly => db_call().await, MerchantStorageScheme::RedisKv => { let redis_fut = async { let kv_result = Box::pin(kv_wrapper::<M, _, _>( self, KvOperation::<M>::Scan(pattern), key, )) .await? .try_into_scan(); kv_result.map(|records| records.into_iter().filter(filter_fn).collect()) }; Box::pin(find_all_combined_kv_database(redis_fut, db_call, limit)).await } }?; let resource_futures = resources .into_iter() .map(|pm| async { pm.convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .collect::<Vec<_>>(); futures::future::try_join_all(resource_futures).await } } #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/configs.rs
crates/storage_impl/src/configs.rs
use diesel_models::configs as storage; use error_stack::report; use hyperswitch_domain_models::configs::ConfigInterface; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store, redis::{ cache, cache::{CacheKind, CONFIG_CACHE}, }, store::ConfigUpdateInternal, CustomResult, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error> { self.router_store.insert_config(config).await } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { self.router_store .update_config_in_database(key, config_update) .await } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { self.router_store .update_config_by_key(key, config_update) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, StorageError> { self.router_store.find_config_by_key_from_db(key).await } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { self.router_store.find_config_by_key(key).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, StorageError> { self.router_store .find_config_by_key_unwrap_or(key, default_config) .await } #[instrument(skip_all)] async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { self.router_store.delete_config_by_key(key).await } } #[async_trait::async_trait] impl<T: DatabaseStore> ConfigInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; let inserted = config .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))?; cache::redact_from_redis_and_publish(self, [CacheKind::Config((&inserted.key).into())]) .await?; Ok(inserted) } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::update_by_key(&conn, key, config_update) .await .map_err(|error| report!(StorageError::from(error))) } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { cache::publish_and_redact(self, CacheKind::Config(key.into()), || { self.update_config_in_database(key, config_update) }) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { let find_config_by_key_from_db = || async { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) }; cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, StorageError> { let find_else_unwrap_or = || async { let conn = connection::pg_connection_write(self).await?; match storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) { Ok(a) => Ok(a), Err(err) => { if err.current_context().is_db_not_found() { default_config .map(|c| { storage::ConfigNew { key: key.to_string(), config: c, } .into() }) .ok_or(err) } else { Err(err) } } } }; cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error)))?; cache::redact_from_redis_and_publish(self, [CacheKind::Config((&deleted.key).into())]) .await?; Ok(deleted) } } #[async_trait::async_trait] impl ConfigInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error> { let mut configs = self.configs.lock().await; let config_new = storage::Config { key: config.key, config: config.config, }; configs.push(config_new.clone()); Ok(config_new) } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error> { self.update_config_by_key(key, config_update).await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error> { let result = self .configs .lock() .await .iter_mut() .find(|c| c.key == key) .ok_or_else(|| { StorageError::ValueNotFound("cannot find config to update".to_string()).into() }) .map(|c| { let config_updated = ConfigUpdateInternal::from(config_update).create_config(c.clone()); *c = config_updated.clone(); config_updated }); result } async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> { let mut configs = self.configs.lock().await; let result = configs .iter() .position(|c| c.key == key) .map(|index| configs.remove(index)) .ok_or_else(|| { StorageError::ValueNotFound("cannot find config to delete".to_string()).into() }); result } async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> { let configs = self.configs.lock().await; let config = configs.iter().find(|c| c.key == key).cloned(); config.ok_or_else(|| StorageError::ValueNotFound("cannot find config".to_string()).into()) } async fn find_config_by_key_unwrap_or( &self, key: &str, _default_config: Option<String>, ) -> CustomResult<storage::Config, Self::Error> { self.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, Self::Error> { self.find_config_by_key(key).await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/redis.rs
crates/storage_impl/src/redis.rs
pub mod cache; pub mod kv_store; pub mod pub_sub; use std::sync::{atomic, Arc}; use router_env::tracing::Instrument; use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface}; #[derive(Clone)] pub struct RedisStore { // Maybe expose the redis_conn via traits instead of the making the field public pub(crate) redis_conn: Arc<redis_interface::RedisConnectionPool>, } impl std::fmt::Debug for RedisStore { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CacheStore") .field("redis_conn", &"Redis conn doesn't implement debug") .finish() } } impl RedisStore { pub async fn new( conf: &redis_interface::RedisSettings, ) -> error_stack::Result<Self, redis_interface::errors::RedisError> { Ok(Self { redis_conn: Arc::new(redis_interface::RedisConnectionPool::new(conf).await?), }) } pub fn set_error_callback(&self, callback: tokio::sync::oneshot::Sender<()>) { let redis_clone = self.redis_conn.clone(); let _task_handle = tokio::spawn( async move { redis_clone.on_error(callback).await; } .in_current_span(), ); } } impl RedisConnInterface for RedisStore { fn get_redis_conn( &self, ) -> error_stack::Result< Arc<redis_interface::RedisConnectionPool>, redis_interface::errors::RedisError, > { if self .redis_conn .is_redis_available .load(atomic::Ordering::SeqCst) { Ok(self.redis_conn.clone()) } else { Err(redis_interface::errors::RedisError::RedisConnectionError.into()) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/reverse_lookup.rs
crates/storage_impl/src/reverse_lookup.rs
use diesel_models::reverse_lookup::ReverseLookup; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for ReverseLookup {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/merchant_key_store.rs
crates/storage_impl/src/merchant_key_store.rs
use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store as domain, merchant_key_store::MerchantKeyStoreInterface, }; use masking::Secret; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::{ cache, cache::{CacheKind, ACCOUNTS_CACHE}, }; use crate::{ kv_router_store, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantKeyStoreInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant_key_store( &self, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { self.router_store .insert_merchant_key_store(merchant_key_store, key) .await } #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { self.router_store .get_merchant_key_store_by_merchant_id(merchant_id, key) .await } #[instrument(skip_all)] async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_key_store_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_key_stores( &self, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { self.router_store .list_multiple_key_stores(merchant_ids, key) .await } async fn get_all_key_stores( &self, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { self.router_store.get_all_key_stores(key, from, to).await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant_key_store( &self, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let conn = pg_accounts_connection_write(self).await?; let merchant_id = merchant_key_store.merchant_id.clone(); merchant_key_store .construct_new() .await .change_context(Self::Error::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(Self::Error::from(error)))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_id.into(), ) .await .change_context(Self::Error::DecryptionError) } #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; let state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::get_or_populate_in_memory( self, &key_store_cache_key, fetch_func, &ACCOUNTS_CACHE, ) .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error> { let delete_func = || async { let conn = pg_accounts_connection_write(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { delete_func().await } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::publish_and_redact( self, CacheKind::Accounts(key_store_cache_key.into()), delete_func, ) .await } } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_key_stores( &self, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores( &conn, merchant_ids, ) .await .map_err(|error| report!(Self::Error::from(error))) }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_id.into(), ) .await .change_context(Self::Error::DecryptionError) })) .await } async fn get_all_key_stores( &self, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores( &conn, from, to, ) .await .map_err(|err| report!(Self::Error::from(err)))?; futures::future::try_join_all(stores.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_id.into(), ) .await .change_context(Self::Error::DecryptionError) })) .await } } #[async_trait::async_trait] impl MerchantKeyStoreInterface for MockDb { type Error = StorageError; async fn insert_merchant_key_store( &self, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let mut locked_merchant_key_store = self.merchant_key_store.lock().await; if locked_merchant_key_store .iter() .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id) { Err(StorageError::DuplicateValue { entity: "merchant_key_store", key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()), })?; } let merchant_key = Conversion::convert(merchant_key_store) .await .change_context(StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); let merchant_id = merchant_key.merchant_id.clone(); merchant_key .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_id.into(), ) .await .change_context(StorageError::DecryptionError) } async fn get_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, StorageError> { self.merchant_key_store .lock() .await .iter() .find(|merchant_key| merchant_key.merchant_id == *merchant_id) .cloned() .ok_or(StorageError::ValueNotFound(String::from( "merchant_key_store", )))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut merchant_key_stores = self.merchant_key_store.lock().await; let index = merchant_key_stores .iter() .position(|mks| mks.merchant_id == *merchant_id) .ok_or(StorageError::ValueNotFound(format!( "No merchant key store found for merchant_id = {merchant_id:?}", )))?; merchant_key_stores.remove(index); Ok(true) } #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all( merchant_key_stores .iter() .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id)) .map(|merchant_key| async { merchant_key .to_owned() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_key.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await } async fn get_all_key_stores( &self, key: &Secret<Vec<u8>>, _from: u32, _to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, key, merchant_key.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) })) .await } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payments.rs
crates/storage_impl/src/payments.rs
pub mod payment_attempt; pub mod payment_intent; use diesel_models::{payment_attempt::PaymentAttempt, PaymentIntent}; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentIntent {} impl KvStorePartition for PaymentAttempt {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/tokenization.rs
crates/storage_impl/src/tokenization.rs
#[cfg(all(feature = "v2", feature = "tokenization_v2"))] use common_utils::errors::CustomResult; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use diesel_models::tokenization as tokenization_diesel; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use error_stack::{report, ResultExt}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use super::MockDb; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use crate::{connection, errors}; use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore}; #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] pub trait TokenizationInterface {} #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub trait TokenizationInterface { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; async fn update_tokenization_record( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; tokenization .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let tokenization = tokenization_diesel::Tokenization::find_by_id(&conn, token) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let domain = tokenization .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(domain) } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let tokenization_record = Conversion::convert(tokenization_record) .await .change_context(errors::StorageError::DecryptionError)?; self.call_database( merchant_key_store, tokenization_record.update_with_id( &conn, tokenization_diesel::TokenizationUpdateInternal::from(tokenization_update), ), ) .await } } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .insert_tokenization(tokenization, merchant_key_store) .await } async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .get_entity_id_vault_id_by_token_id(token, merchant_key_store) .await } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .update_tokenization_record( tokenization_record, tokenization_update, merchant_key_store, ) .await } } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl TokenizationInterface for MockDb { async fn insert_tokenization( &self, _tokenization: hyperswitch_domain_models::tokenization::Tokenization, _merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn get_entity_id_vault_id_by_token_id( &self, _token: &common_utils::id_type::GlobalTokenId, _merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_tokenization_record( &self, _tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, _tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, _merchant_key_store: &MerchantKeyStore, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl TokenizationInterface for MockDb {} #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {} #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payments/payment_attempt.rs
crates/storage_impl/src/payments/payment_attempt.rs
use common_utils::{errors::CustomResult, ext_traits::AsyncExt}; #[cfg(feature = "v1")] use common_utils::{fallback_reverse_lookup_not_found, types::ConnectorTransactionId}; use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, MandateDetails as DieselMandateDetails, MerchantStorageScheme, }, kv, payment_attempt::PaymentAttempt as DieselPaymentAttempt, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "olap"))] use futures::future::{try_join_all, FutureExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::behaviour::ReverseConversion; use hyperswitch_domain_models::{ behaviour::Conversion, mandates::{MandateAmountData, MandateDataType, MandateDetails}, merchant_key_store::MerchantKeyStore, payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate}, }; #[cfg(all(feature = "v1", feature = "olap"))] use hyperswitch_domain_models::{ payments::payment_attempt::PaymentListFilters, payments::PaymentIntent, }; #[cfg(feature = "v2")] use label::*; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; #[cfg(feature = "v2")] use crate::kv_router_store::{FilterResourceParams, FindResourceBy, UpdateResourceParams}; use crate::{ diesel_error_to_data_error, errors, errors::RedisErrorExt, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get}, DataModelExt, DatabaseStore, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttempt, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_attempt = payment_attempt .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; diesel_payment_attempt .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, merchant_key_store: &MerchantKeyStore, payment_attempt: PaymentAttempt, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; payment_attempt .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| { let new_error = diesel_error_to_data_error(*error.current_context()); error.change_context(new_error) })? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; this.convert() .await .change_context(errors::StorageError::EncryptionError)? .update_with_attempt_id(&conn, payment_attempt.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_attempt( &self, merchant_key_store: &MerchantKeyStore, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update_with_attempt_id( &conn, diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt), ) .await .map_err(|error| { let new_error = diesel_error_to_data_error(*error.current_context()); error.change_context(new_error) })? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &ConnectorTransactionId, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id( &conn, connector_transaction_id, payment_id, merchant_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }).await? } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, merchant_key_store: &MerchantKeyStore, payment_id: &common_utils::id_type::GlobalPaymentId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id( &conn, payment_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_by_merchant_id_connector_txn_id( &conn, merchant_id, connector_txn_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_txn_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_profile_id_connector_transaction_id( &conn, profile_id, connector_txn_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_by_payment_id_merchant_id_attempt_id( &conn, payment_id, merchant_id, attempt_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentListFilters, errors::StorageError> { use hyperswitch_domain_models::behaviour::Conversion; let conn = pg_connection_read(self).await?; let intents = try_join_all(pi.iter().map(|pi| async { Conversion::convert(pi.clone()) .await .change_context(errors::StorageError::EncryptionError) })) .await?; DieselPaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( |( connector, currency, status, payment_method, payment_method_type, authentication_type, )| PaymentListFilters { connector, currency, status, payment_method, payment_method_type, authentication_type, }, ) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_by_merchant_id_preprocessing_id( &conn, merchant_id, preprocessing_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(|v| { try_join_all(v.into_iter().map(|diesel_payment_attempt| { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) })) .map(|join_result| { join_result.change_context(errors::StorageError::DecryptionError) }) })? .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; let key_manager_state = self .get_keymanager_state() .attach_printable("Missing KeyManagerState")?; DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_map(|diesel_payment_attempt| async { PaymentAttempt::convert_back( key_manager_state, diesel_payment_attempt, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await? } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempt_by_id( &self, merchant_key_store: &MerchantKeyStore, attempt_id: &common_utils::id_type::GlobalAttemptId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_id(&conn, attempt_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempts_by_payment_intent_id( &self, payment_id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> { use common_utils::ext_traits::AsyncExt; let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_payment_id(&conn, payment_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|payment_attempts| async { let mut domain_payment_attempts = Vec::with_capacity(payment_attempts.len()); for attempt in payment_attempts.into_iter() { domain_payment_attempts.push( attempt .convert( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_payment_attempts) }) .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method: Option<Vec<common_enums::PaymentMethod>>, payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, card_discovery: Option<Vec<common_enums::CardDiscovery>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; let connector_strings = connector.as_ref().map(|connector| { connector .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() }); DieselPaymentAttempt::get_total_count_of_attempts( &conn, merchant_id, active_attempt_ids, connector_strings, payment_method, payment_method_type, authentication_type, merchant_connector_id, card_network, card_discovery, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<common_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; DieselPaymentAttempt::get_total_count_of_attempts( &conn, merchant_id, active_attempt_ids, connector .as_ref() .map(|vals| vals.iter().map(|v| v.to_string()).collect()), payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, card_network, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttempt, storage_scheme: MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_attempt(payment_attempt, storage_scheme, merchant_key_store) .await } MerchantStorageScheme::RedisKv => { let merchant_id = payment_attempt.merchant_id.clone(); let payment_id = payment_attempt.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let key_str = key.to_string(); let created_attempt = PaymentAttempt { payment_id: payment_attempt.payment_id.clone(), merchant_id: payment_attempt.merchant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, net_amount: payment_attempt.net_amount.clone(), currency: payment_attempt.currency, save_to_locker: payment_attempt.save_to_locker, connector: payment_attempt.connector.clone(), error_message: payment_attempt.error_message.clone(), offer_amount: payment_attempt.offer_amount, payment_method_id: payment_attempt.payment_method_id.clone(), payment_method: payment_attempt.payment_method, connector_transaction_id: None, capture_method: payment_attempt.capture_method, capture_on: payment_attempt.capture_on, confirm: payment_attempt.confirm, authentication_type: payment_attempt.authentication_type, created_at: payment_attempt.created_at, modified_at: payment_attempt.created_at, last_synced: payment_attempt.last_synced, amount_to_capture: payment_attempt.amount_to_capture, cancellation_reason: payment_attempt.cancellation_reason.clone(), mandate_id: payment_attempt.mandate_id.clone(), browser_info: payment_attempt.browser_info.clone(), payment_token: payment_attempt.payment_token.clone(), error_code: payment_attempt.error_code.clone(), connector_metadata: payment_attempt.connector_metadata.clone(), payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, payment_method_data: payment_attempt.payment_method_data.clone(), business_sub_label: payment_attempt.business_sub_label.clone(), straight_through_algorithm: payment_attempt.straight_through_algorithm.clone(), mandate_details: payment_attempt.mandate_details.clone(), preprocessing_step_id: payment_attempt.preprocessing_step_id.clone(), error_reason: payment_attempt.error_reason.clone(), multiple_capture_count: payment_attempt.multiple_capture_count, connector_response_reference_id: None, charge_id: None, amount_capturable: payment_attempt.amount_capturable, updated_by: storage_scheme.to_string(), authentication_data: payment_attempt.authentication_data.clone(), encoded_data: payment_attempt.encoded_data.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), unified_code: payment_attempt.unified_code.clone(), unified_message: payment_attempt.unified_message.clone(), external_three_ds_authentication_attempted: payment_attempt .external_three_ds_authentication_attempted, authentication_connector: payment_attempt.authentication_connector.clone(), authentication_id: payment_attempt.authentication_id.clone(), mandate_data: payment_attempt.mandate_data.clone(), payment_method_billing_address_id: payment_attempt .payment_method_billing_address_id .clone(), fingerprint_id: payment_attempt.fingerprint_id.clone(), client_source: payment_attempt.client_source.clone(),
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payments/payment_intent.rs
crates/storage_impl/src/payments/payment_intent.rs
#[cfg(feature = "olap")] use api_models::payments::{AmountFilter, Order, SortBy, SortOn}; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use common_utils::ext_traits::{AsyncExt, Encode}; #[cfg(feature = "v2")] use common_utils::fallback_reverse_lookup_not_found; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; #[cfg(feature = "v1")] use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate; #[cfg(feature = "v2")] use diesel_models::payment_intent::PaymentIntentUpdateInternal; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; #[cfg(feature = "v2")] use diesel_models::reverse_lookup::ReverseLookupNew; #[cfg(all(feature = "v1", feature = "olap"))] use diesel_models::schema::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; #[cfg(all(feature = "v2", feature = "olap"))] use diesel_models::schema_v2::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent, }; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "olap"))] use futures::future::try_join_all; #[cfg(feature = "olap")] use hyperswitch_domain_models::payments::{ payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, }; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{ payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, }; use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use crate::connection; use crate::{ diesel_error_to_data_error, errors::{RedisErrorExt, StorageError}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DatabaseStore, }; #[cfg(feature = "v2")] use crate::{errors, lookup::ReverseLookupInterface}; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] async fn insert_payment_intent( &self, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let merchant_id = payment_intent.merchant_id.clone(); let payment_id = payment_intent.get_id().to_owned(); let field = payment_intent.get_id().get_hash_key_for_kv_store(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_intent(payment_intent, merchant_key_store, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let new_payment_intent = payment_intent .clone() .construct_new() .await .change_context(StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( new_payment_intent, ))), }, }; let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HSetNx( &field, &diesel_payment_intent, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payment_intent", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_intent), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[cfg(feature = "v2")] async fn insert_payment_intent( &self, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_intent(payment_intent, merchant_key_store, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let id = payment_intent.id.clone(); let key = PartitionKey::GlobalPaymentId { id: &id }; let field = format!("pi_{}", id.get_string_repr()); let key_str = key.to_string(); let new_payment_intent = payment_intent .clone() .construct_new() .await .change_context(StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( new_payment_intent, ))), }, }; let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; if let Some(merchant_reference_id) = &payment_intent.merchant_reference_id { let reverse_lookup = ReverseLookupNew { lookup_id: format!( "pi_merchant_reference_{}_{}", payment_intent.profile_id.get_string_repr(), merchant_reference_id.get_string_repr() ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_intent".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; } match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HSetNx( &field, &diesel_payment_intent, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payment_intent", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_intent), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( merchant_id, constraints, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_intent( &self, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let merchant_id = this.merchant_id.clone(); let payment_id = this.get_id().to_owned(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("pi_{}", this.get_id().get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( this, payment_intent_update, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update); let origin_diesel_intent = this .convert() .await .change_context(StorageError::EncryptionError)?; let diesel_intent = diesel_intent_update .clone() .apply_changeset(origin_diesel_intent.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_intent .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( kv::PaymentIntentUpdateMems { orig: origin_diesel_intent, update_data: diesel_intent_update, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; let payment_intent = PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_intent( &self, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( this, payment_intent_update, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let id = this.id.clone(); let merchant_id = this.merchant_id.clone(); let key = PartitionKey::GlobalPaymentId { id: &id }; let field = format!("pi_{}", id.get_string_repr()); let key_str = key.to_string(); let diesel_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent_update) .change_context(StorageError::DeserializationFailed)?; let origin_diesel_intent = this .convert() .await .change_context(StorageError::EncryptionError)?; let diesel_intent = diesel_intent_update .clone() .apply_changeset(origin_diesel_intent.clone()); let redis_value = diesel_intent .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( kv::PaymentIntentUpdateMems { orig: origin_diesel_intent, update_data: diesel_intent_update, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; let payment_intent = PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Find, )) .await; let diesel_payment_intent = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = payment_id.get_hash_key_for_kv_store(); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Find, )) .await; let database_call = || async { let conn: bb8::PooledConnection< '_, async_bb8_diesel::ConnectionManager<diesel::PgConnection>, > = pg_connection_read(self).await?; DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let diesel_payment_intent = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalPaymentId { id }; let field = format!("pi_{}", id.get_string_repr()); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intent_by_constraints( merchant_id, filters, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intents_by_time_range_constraints( merchant_id, time_range, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { self.router_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( merchant_id, filters, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { self.router_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { self.router_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, merchant_key_store: &MerchantKeyStore, storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_intent_by_merchant_reference_id_profile_id( merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pi_merchant_reference_{}_{}", profile_id.get_string_repr(), merchant_reference_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, *storage_scheme) .await, self.router_store .find_payment_intent_by_merchant_reference_id_profile_id( merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; let database_call = || async { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_merchant_reference_id_profile_id( &conn, merchant_reference_id, profile_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let diesel_payment_intent = Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError) } } } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payment_intent( &self, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent = payment_intent .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_intent( &self, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = DieselPaymentIntentUpdate::from(payment_intent); let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_intent( &self, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent) .change_context(StorageError::DeserializationFailed)?; let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|diesel_payment_intent| async { PaymentIntent::convert_back( self.get_keymanager_state() .attach_printable("Missing KeyManagerState")?, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| {
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payouts/payout_attempt.rs
crates/storage_impl/src/payouts/payout_attempt.rs
use std::str::FromStr; use api_models::enums::PayoutConnectors; use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found}; use diesel_models::{ enums::MerchantStorageScheme, kv, payout_attempt::{ PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew, PayoutAttemptUpdate as DieselPayoutAttemptUpdate, }, reverse_lookup::ReverseLookup, ReverseLookupNew, }; use error_stack::ResultExt; use hyperswitch_domain_models::payouts::{ payout_attempt::{ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate, PayoutListFilters, }, payouts::Payouts, }; use redis_interface::HsetnxReply; use router_env::{instrument, logger, tracing}; use crate::{ diesel_error_to_data_error, errors, errors::RedisErrorExt, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_payout_attempt( &self, new_payout_attempt: PayoutAttemptNew, payouts: &Payouts, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payout_attempt(new_payout_attempt, payouts, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let merchant_id = new_payout_attempt.merchant_id.clone(); let payout_attempt_id = new_payout_attempt.payout_id.clone(); let key = PartitionKey::MerchantIdPayoutAttemptId { merchant_id: &merchant_id, payout_attempt_id: payout_attempt_id.get_string_repr(), }; let key_str = key.to_string(); let created_attempt = PayoutAttempt { payout_attempt_id: new_payout_attempt.payout_attempt_id.clone(), payout_id: new_payout_attempt.payout_id.clone(), additional_payout_method_data: new_payout_attempt .additional_payout_method_data .clone(), customer_id: new_payout_attempt.customer_id.clone(), merchant_id: new_payout_attempt.merchant_id.clone(), address_id: new_payout_attempt.address_id.clone(), connector: new_payout_attempt.connector.clone(), connector_payout_id: new_payout_attempt.connector_payout_id.clone(), payout_token: new_payout_attempt.payout_token.clone(), status: new_payout_attempt.status, is_eligible: new_payout_attempt.is_eligible, error_message: new_payout_attempt.error_message.clone(), error_code: new_payout_attempt.error_code.clone(), business_country: new_payout_attempt.business_country, business_label: new_payout_attempt.business_label.clone(), created_at: new_payout_attempt.created_at, last_modified_at: new_payout_attempt.last_modified_at, profile_id: new_payout_attempt.profile_id.clone(), merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(), routing_info: new_payout_attempt.routing_info.clone(), unified_code: new_payout_attempt.unified_code.clone(), unified_message: new_payout_attempt.unified_message.clone(), merchant_order_reference_id: new_payout_attempt .merchant_order_reference_id .clone(), payout_connector_metadata: new_payout_attempt.payout_connector_metadata.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PayoutAttempt( new_payout_attempt.to_storage_model(), )), }, }; // Reverse lookup for payout_attempt_id let field = format!("poa_{}", created_attempt.payout_attempt_id); let reverse_lookup = ReverseLookupNew { lookup_id: format!( "poa_{}_{}", &created_attempt.merchant_id.get_string_repr(), &created_attempt.payout_attempt_id, ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payout_attempt".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>( self, KvOperation::<DieselPayoutAttempt>::HSetNx( &field, &created_attempt.clone().to_storage_model(), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payout attempt", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_attempt), Err(error) => Err(error.change_context(errors::StorageError::KVError)), } } } } #[instrument(skip_all)] async fn update_payout_attempt( &self, this: &PayoutAttempt, payout_update: PayoutAttemptUpdate, payouts: &Payouts, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let key = PartitionKey::MerchantIdPayoutAttemptId { merchant_id: &this.merchant_id, payout_attempt_id: this.payout_id.get_string_repr(), }; let field = format!("poa_{}", this.payout_attempt_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Update(key.clone(), &field, None), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payout_attempt(this, payout_update, payouts, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_payout_update = payout_update.clone().to_storage_model(); let origin_diesel_payout = this.clone().to_storage_model(); let diesel_payout = diesel_payout_update .clone() .apply_changeset(origin_diesel_payout.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_payout .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PayoutAttemptUpdate( kv::PayoutAttemptUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, }, )), }, }; let updated_attempt = PayoutAttempt::from_storage_model( payout_update .to_storage_model() .apply_changeset(this.clone().to_storage_model()), ); let old_connector_payout_id = this.connector_payout_id.clone(); match ( old_connector_payout_id, updated_attempt.connector_payout_id.clone(), ) { (Some(old), Some(new)) if old != new => { add_connector_payout_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.payout_attempt_id.as_str(), new.as_str(), storage_scheme, ) .await?; } (None, Some(new)) => { add_connector_payout_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.payout_attempt_id.as_str(), new.as_str(), storage_scheme, ) .await?; } _ => {} } Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(PayoutAttempt::from_storage_model(diesel_payout)) } } } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!("poa_{}_{payout_attempt_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await }, )) .await } } } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "po_conn_payout_{}_{connector_payout_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await }, )) .await } } } #[instrument(skip_all)] async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutListFilters, errors::StorageError> { self.router_store .get_filters_for_payouts(payouts, merchant_id, storage_scheme) .await } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_order_reference_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { self.router_store .find_payout_attempt_by_merchant_id_merchant_order_reference_id( merchant_id, merchant_order_reference_id, storage_scheme, ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_payout_attempt( &self, new: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; new.to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) } #[instrument(skip_all)] async fn update_payout_attempt( &self, this: &PayoutAttempt, payout: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update_with_attempt_id(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_payout_attempt_id( &conn, merchant_id, payout_attempt_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_connector_payout_id( &conn, merchant_id, connector_payout_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PayoutListFilters, errors::StorageError> { let conn = pg_connection_read(self).await?; let payouts = payouts .iter() .cloned() .map(|payouts| payouts.to_storage_model()) .collect::<Vec<diesel_models::Payouts>>(); DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( |(connector, currency, status, payout_method)| PayoutListFilters { connector: connector .iter() .filter_map(|c| { PayoutConnectors::from_str(c) .map_err(|e| { logger::error!( "Failed to parse payout connector '{}' - {}", c, e ); }) .ok() }) .collect(), currency, status, payout_method, }, ) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_order_reference_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_merchant_order_reference_id( &conn, merchant_id, merchant_order_reference_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } impl DataModelExt for PayoutAttempt { type StorageModel = DieselPayoutAttempt; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutAttempt { payout_attempt_id: self.payout_attempt_id, payout_id: self.payout_id, customer_id: self.customer_id, merchant_id: self.merchant_id, address_id: self.address_id, connector: self.connector, connector_payout_id: self.connector_payout_id, payout_token: self.payout_token, status: self.status, is_eligible: self.is_eligible, error_message: self.error_message, error_code: self.error_code, business_country: self.business_country, business_label: self.business_label, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, unified_code: self.unified_code, unified_message: self.unified_message, additional_payout_method_data: self.additional_payout_method_data, merchant_order_reference_id: self.merchant_order_reference_id, payout_connector_metadata: self.payout_connector_metadata, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_attempt_id: storage_model.payout_attempt_id, payout_id: storage_model.payout_id, customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, address_id: storage_model.address_id, connector: storage_model.connector, connector_payout_id: storage_model.connector_payout_id, payout_token: storage_model.payout_token, status: storage_model.status, is_eligible: storage_model.is_eligible, error_message: storage_model.error_message, error_code: storage_model.error_code, business_country: storage_model.business_country, business_label: storage_model.business_label, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, additional_payout_method_data: storage_model.additional_payout_method_data, merchant_order_reference_id: storage_model.merchant_order_reference_id, payout_connector_metadata: storage_model.payout_connector_metadata, } } } impl DataModelExt for PayoutAttemptNew { type StorageModel = DieselPayoutAttemptNew; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutAttemptNew { payout_attempt_id: self.payout_attempt_id, payout_id: self.payout_id, customer_id: self.customer_id, merchant_id: self.merchant_id, address_id: self.address_id, connector: self.connector, connector_payout_id: self.connector_payout_id, payout_token: self.payout_token, status: self.status, is_eligible: self.is_eligible, error_message: self.error_message, error_code: self.error_code, business_country: self.business_country, business_label: self.business_label, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, unified_code: self.unified_code, unified_message: self.unified_message, additional_payout_method_data: self.additional_payout_method_data, merchant_order_reference_id: self.merchant_order_reference_id, payout_connector_metadata: self.payout_connector_metadata, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_attempt_id: storage_model.payout_attempt_id, payout_id: storage_model.payout_id, customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, address_id: storage_model.address_id, connector: storage_model.connector, connector_payout_id: storage_model.connector_payout_id, payout_token: storage_model.payout_token, status: storage_model.status, is_eligible: storage_model.is_eligible, error_message: storage_model.error_message, error_code: storage_model.error_code, business_country: storage_model.business_country, business_label: storage_model.business_label, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, additional_payout_method_data: storage_model.additional_payout_method_data, merchant_order_reference_id: storage_model.merchant_order_reference_id, payout_connector_metadata: storage_model.payout_connector_metadata, } } } impl DataModelExt for PayoutAttemptUpdate { type StorageModel = DieselPayoutAttemptUpdate; fn to_storage_model(self) -> Self::StorageModel { match self { Self::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, } => DieselPayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, }, Self::PayoutTokenUpdate { payout_token } => { DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token } } Self::BusinessUpdate { business_country, business_label, address_id, customer_id, } => DieselPayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, }, Self::UpdateRouting { connector, routing_info, merchant_connector_id, } => DieselPayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, }, Self::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => DieselPayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, }, Self::ManualUpdate { status, error_code, error_message, unified_code, unified_message, connector_payout_id, } => DieselPayoutAttemptUpdate::ManualUpdate { status, error_code, error_message, unified_code, unified_message, connector_payout_id, }, } } #[allow(clippy::todo)] fn from_storage_model(_storage_model: Self::StorageModel) -> Self { todo!("Reverse map should no longer be needed") } } #[inline] #[instrument(skip_all)] async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>( store: &KVRouterStore<T>, key: &str, merchant_id: &common_utils::id_type::MerchantId, updated_attempt_attempt_id: &str, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let field = format!("poa_{updated_attempt_attempt_id}"); let reverse_lookup_new = ReverseLookupNew { lookup_id: format!( "po_conn_payout_{}_{}", merchant_id.get_string_repr(), connector_payout_id ), pk_id: key.to_owned(), sk_id: field.clone(), source: "payout_attempt".to_string(), updated_by: storage_scheme.to_string(), }; store .insert_reverse_lookup(reverse_lookup_new, storage_scheme) .await }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/storage_impl/src/payouts/payouts.rs
crates/storage_impl/src/payouts/payouts.rs
#[cfg(feature = "olap")] use api_models::enums::PayoutConnectors; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use common_utils::ext_traits::Encode; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; #[cfg(all(feature = "v1", feature = "olap"))] use diesel::{JoinOnDsl, NullableExpressionMethods}; #[cfg(feature = "olap")] use diesel_models::{ address::Address as DieselAddress, customers::Customer as DieselCustomer, enums as storage_enums, query::generics::db_metrics, schema::payouts::dsl as po_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, kv, payouts::{ Payouts as DieselPayouts, PayoutsNew as DieselPayoutsNew, PayoutsUpdate as DieselPayoutsUpdate, }, }; #[cfg(all(feature = "olap", feature = "v1"))] use diesel_models::{ payout_attempt::PayoutAttempt as DieselPayoutAttempt, schema::{address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl}, }; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payouts::PayoutFetchConstraints; use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttempt, payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate}, }; use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use crate::connection; #[cfg(all(feature = "olap", feature = "v1"))] use crate::store::schema::{ address::all_columns as addr_all_columns, customers::all_columns as cust_all_columns, payout_attempt::all_columns as poa_all_columns, payouts::all_columns as po_all_columns, }; use crate::{ diesel_error_to_data_error, errors::{RedisErrorExt, StorageError}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payout( &self, new: PayoutsNew, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store.insert_payout(new, storage_scheme).await } MerchantStorageScheme::RedisKv => { let merchant_id = new.merchant_id.clone(); let payout_id = new.payout_id.clone(); let key = PartitionKey::MerchantIdPayoutId { merchant_id: &merchant_id, payout_id: &payout_id, }; let key_str = key.to_string(); let field = format!("po_{}", new.payout_id.get_string_repr()); let created_payout = Payouts { payout_id: new.payout_id.clone(), merchant_id: new.merchant_id.clone(), customer_id: new.customer_id.clone(), address_id: new.address_id.clone(), payout_type: new.payout_type, payout_method_id: new.payout_method_id.clone(), amount: new.amount, destination_currency: new.destination_currency, source_currency: new.source_currency, description: new.description.clone(), recurring: new.recurring, auto_fulfill: new.auto_fulfill, return_url: new.return_url.clone(), entity_type: new.entity_type, metadata: new.metadata.clone(), created_at: new.created_at, last_modified_at: new.last_modified_at, profile_id: new.profile_id.clone(), status: new.status, attempt_count: new.attempt_count, confirm: new.confirm, payout_link_id: new.payout_link_id.clone(), client_secret: new.client_secret.clone(), priority: new.priority, organization_id: new.organization_id.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())), }, }; match Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HSetNx( &field, &created_payout.clone().to_storage_model(), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payouts", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_payout), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[instrument(skip_all)] async fn update_payout( &self, this: &Payouts, payout_update: PayoutsUpdate, payout_attempt: &PayoutAttempt, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let key = PartitionKey::MerchantIdPayoutId { merchant_id: &this.merchant_id, payout_id: &this.payout_id, }; let field = format!("po_{}", this.payout_id.get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Update(key.clone(), &field, None), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payout(this, payout_update, payout_attempt, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_payout_update = payout_update.to_storage_model(); let origin_diesel_payout = this.clone().to_storage_model(); let diesel_payout = diesel_payout_update .clone() .apply_changeset(origin_diesel_payout.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_payout .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, })), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; Ok(Payouts::from_storage_model(diesel_payout)) } } } #[instrument(skip_all)] async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPayoutId { merchant_id, payout_id, }; let field = format!("po_{}", payout_id.get_string_repr()); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } } .map(Payouts::from_storage_model) } #[instrument(skip_all)] async fn find_optional_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { let maybe_payouts = database_call().await?; Ok(maybe_payouts.filter(|payout| &payout.payout_id == payout_id)) } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPayoutId { merchant_id, payout_id, }; let field = format!("po_{}", payout_id.get_string_repr()); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HGet(&field), key, )) .await? .try_into_hget() .map(Some) }, database_call, )) .await } } .map(|payout| payout.map(Payouts::from_storage_model)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { self.router_store .filter_payouts_by_constraints(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>, StorageError, > { self.router_store .filter_payouts_and_attempts(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] #[instrument[skip_all]] async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { self.router_store .filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme) .await } #[cfg(feature = "olap")] async fn get_total_count_of_filtered_payouts( &self, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<PayoutConnectors>>, currency: Option<Vec<storage_enums::Currency>>, status: Option<Vec<storage_enums::PayoutStatus>>, payout_method: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, StorageError> { self.router_store .get_total_count_of_filtered_payouts( merchant_id, active_payout_ids, connector, currency, status, payout_method, ) .await } #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> { self.router_store .filter_active_payout_ids_by_constraints(merchant_id, constraints) .await } #[cfg(feature = "olap")] async fn get_payout_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, StorageError> { self.router_store .get_payout_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payout( &self, new: PayoutsNew, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_write(self).await?; new.to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) } #[instrument(skip_all)] async fn update_payout( &self, this: &Payouts, payout: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) } #[instrument(skip_all)] async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_read(self).await?; DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map(Payouts::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn find_optional_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, StorageError> { let conn = pg_connection_read(self).await?; DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map(|x| x.map(Payouts::from_storage_model)) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); //[#350]: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut query = <DieselPayouts as HasTable>::table() .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); match filters { PayoutFetchConstraints::Single { payout_id } => { query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned())); } PayoutFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(po_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(po_dsl::profile_id.eq(profile_id.clone())); } query = match (params.starting_at, params.starting_after_id.as_ref()) { (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payout_by_merchant_id_payout_id( merchant_id, starting_after_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, params.ending_before_id.as_ref()) { (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payout_by_merchant_id_payout_id( merchant_id, ending_before_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); if let Some(currency) = &params.currency { query = query.filter(po_dsl::destination_currency.eq_any(currency.clone())); } if let Some(status) = &params.status { query = query.filter(po_dsl::status.eq_any(status.clone())); } } } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>( query.get_results_async::<DieselPayouts>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map(|payouts| { payouts .into_iter() .map(Payouts::from_storage_model) .collect::<Vec<Payouts>>() }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payout records"), ) .into() }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>, StorageError, > { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPayouts::table() .inner_join( diesel_models::schema::payout_attempt::table .on(poa_dsl::payout_id.eq(po_dsl::payout_id)), ) .left_join( diesel_models::schema::customers::table .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)), ) .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned())) .left_outer_join( diesel_models::schema::address::table .on(add_dsl::address_id.nullable().eq(po_dsl::address_id)), ) .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); query = match filters { PayoutFetchConstraints::Single { payout_id } => { query.filter(po_dsl::payout_id.eq(payout_id.to_owned())) } PayoutFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(po_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(po_dsl::profile_id.eq(profile_id.clone())); } if let Some(merchant_order_reference_id_filter) = &params.merchant_order_reference_id { query = query.filter( poa_dsl::merchant_order_reference_id .eq(merchant_order_reference_id_filter.clone()), ); } query = match (params.starting_at, params.starting_after_id.as_ref()) { (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { let starting_at = self .find_payout_by_merchant_id_payout_id( merchant_id, starting_after_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, params.ending_before_id.as_ref()) { (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { let ending_at = self .find_payout_by_merchant_id_payout_id( merchant_id, ending_before_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); if let Some(currency) = &params.currency { query = query.filter(po_dsl::destination_currency.eq_any(currency.clone())); } let connectors = params .connector .as_ref() .map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>()); query = match connectors { Some(conn_filters) if !conn_filters.is_empty() => { query.filter(poa_dsl::connector.eq_any(conn_filters)) } _ => query, }; query = match &params.status { Some(status_filters) if !status_filters.is_empty() => { query.filter(po_dsl::status.eq_any(status_filters.clone())) } _ => query, }; query = match &params.payout_method { Some(payout_method) if !payout_method.is_empty() => { query.filter(po_dsl::payout_type.eq_any(payout_method.clone())) } _ => query, }; query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .select(( po_all_columns, poa_all_columns, cust_all_columns.nullable(), addr_all_columns.nullable(), )) .get_results_async::<( DieselPayouts, DieselPayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>(conn) .await .map(|results| { results .into_iter() .map(|(pi, pa, c, add)| { ( Payouts::from_storage_model(pi), PayoutAttempt::from_storage_model(pa), c, add, ) }) .collect() }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payout records"), ) .into() }) } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, _merchant_id: &common_utils::id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>, StorageError, > { todo!() } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { let payout_filters = (*time_range).into(); self.filter_payouts_by_constraints(merchant_id, &payout_filters, storage_scheme) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_total_count_of_filtered_payouts( &self, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<PayoutConnectors>>, currency: Option<Vec<storage_enums::Currency>>, status: Option<Vec<storage_enums::PayoutStatus>>, payout_type: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(StorageError::DatabaseConnectionError)?; let connector_strings = connector.as_ref().map(|connectors| { connectors .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() }); DieselPayouts::get_total_count_of_payouts( &conn, merchant_id, active_payout_ids, connector_strings, currency, status, payout_type, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_active_payout_ids_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPayouts::table() .inner_join( diesel_models::schema::payout_attempt::table .on(poa_dsl::payout_id.eq(po_dsl::payout_id)), ) .left_join( diesel_models::schema::customers::table .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)), ) .select(po_dsl::payout_id) .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); query = match constraints { PayoutFetchConstraints::Single { payout_id } => { query.filter(po_dsl::payout_id.eq(payout_id.to_owned())) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true