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/api_models/src/gsm.rs | crates/api_models/src/gsm.rs | use utoipa::ToSchema;
use crate::enums as api_enums;
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GsmCreateRequest {
/// The connector through which payment has gone through
#[schema(value_type = Connector)]
pub connector: api_enums::Connector,
/// The flow in which the code and message occurred for a connector
pub flow: String,
/// The sub_flow in which the code and message occurred for a connector
pub sub_flow: String,
/// code received from the connector
pub code: String,
/// message received from the connector
pub message: String,
/// status provided by the router
pub status: String,
/// optional error provided by the router
pub router_error: Option<String>,
/// decision to be taken for auto retries flow
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
#[schema(value_type = GsmDecision)]
pub decision: api_enums::GsmDecision,
/// indicates if step_up retry is possible
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
pub step_up_possible: bool,
/// error code unified across the connectors
pub unified_code: Option<String>,
/// error message unified across the connectors
pub unified_message: Option<String>,
/// category in which error belongs to
#[schema(value_type = Option<ErrorCategory>)]
pub error_category: Option<api_enums::ErrorCategory>,
/// indicates if retry with pan is possible
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
pub clear_pan_possible: bool,
/// Indicates the GSM feature associated with the request,
/// such as retry mechanisms or other specific functionalities provided by the system.
#[schema(value_type = Option<GsmFeature>)]
pub feature: Option<api_enums::GsmFeature>,
/// Contains the data relevant to the specified GSM feature, if applicable.
/// For example, if the `feature` is `Retry`, this will include configuration
/// details specific to the retry behavior.
#[schema(value_type = Option<GsmFeatureData>)]
pub feature_data: Option<common_types::domain::GsmFeatureData>,
/// Code that identifies the specific cause for a failure within a broader error category such as `INVALID_EXPIRY_DATE`, `INVALID_CARD_NUMBER`, or `INSUFFICIENT_FUNDS`.
#[schema(value_type = Option<StandardisedCode>)]
pub standardised_code: Option<api_enums::StandardisedCode>,
/// A detailed description of the error intended for debugging, analytics, and support teams.
pub description: Option<String>,
/// A user-friendly message that can be safely displayed to the customer.
/// This message provides guidance on what the user should do to
/// resolve the issue.
pub user_guidance_message: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GsmRetrieveRequest {
/// The connector through which payment has gone through
#[schema(value_type = Connector)]
pub connector: api_enums::Connector,
/// The flow in which the code and message occurred for a connector
pub flow: String,
/// The sub_flow in which the code and message occurred for a connector
pub sub_flow: String,
/// code received from the connector
pub code: String,
/// message received from the connector
pub message: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GsmUpdateRequest {
/// The connector through which payment has gone through
pub connector: String,
/// The flow in which the code and message occurred for a connector
pub flow: String,
/// The sub_flow in which the code and message occurred for a connector
pub sub_flow: String,
/// code received from the connector
pub code: String,
/// message received from the connector
pub message: String,
/// status provided by the router
pub status: Option<String>,
/// optional error provided by the router
pub router_error: Option<String>,
/// decision to be taken for auto retries flow
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
#[schema(value_type = Option<GsmDecision>)]
pub decision: Option<api_enums::GsmDecision>,
/// indicates if step_up retry is possible
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
pub step_up_possible: Option<bool>,
/// error code unified across the connectors
pub unified_code: Option<String>,
/// error message unified across the connectors
pub unified_message: Option<String>,
/// category in which error belongs to
#[schema(value_type = Option<ErrorCategory>)]
pub error_category: Option<api_enums::ErrorCategory>,
/// indicates if retry with pan is possible
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
pub clear_pan_possible: Option<bool>,
/// Indicates the GSM feature associated with the request,
/// such as retry mechanisms or other specific functionalities provided by the system.
#[schema(value_type = Option<GsmFeature>)]
pub feature: Option<api_enums::GsmFeature>,
/// Contains the data relevant to the specified GSM feature, if applicable.
/// For example, if the `feature` is `Retry`, this will include configuration
/// details specific to the retry behavior.
#[schema(value_type = Option<GsmFeatureData>)]
pub feature_data: Option<common_types::domain::GsmFeatureData>,
/// Code that identifies the specific cause for a failure within a broader error category such as `INVALID_EXPIRY_DATE`, `INVALID_CARD_NUMBER`, or `INSUFFICIENT_FUNDS`.
#[schema(value_type = Option<StandardisedCode>)]
pub standardised_code: Option<api_enums::StandardisedCode>,
/// A detailed description of the error intended for debugging, analytics, and support teams.
pub description: Option<String>,
/// A user-friendly message that can be safely displayed to the customer.
/// This message provides guidance on what the user should do to
/// resolve the issue.
pub user_guidance_message: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GsmDeleteRequest {
/// The connector through which payment has gone through
pub connector: String,
/// The flow in which the code and message occurred for a connector
pub flow: String,
/// The sub_flow in which the code and message occurred for a connector
pub sub_flow: String,
/// code received from the connector
pub code: String,
/// message received from the connector
pub message: String,
}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct GsmDeleteResponse {
pub gsm_rule_delete: bool,
/// The connector through which payment has gone through
pub connector: String,
/// The flow in which the code and message occurred for a connector
pub flow: String,
/// The sub_flow in which the code and message occurred for a connector
pub sub_flow: String,
/// code received from the connector
pub code: String,
}
#[derive(serde::Serialize, Debug, ToSchema)]
pub struct GsmResponse {
/// The connector through which payment has gone through
pub connector: String,
/// The flow in which the code and message occurred for a connector
pub flow: String,
/// The sub_flow in which the code and message occurred for a connector
pub sub_flow: String,
/// code received from the connector
pub code: String,
/// message received from the connector
pub message: String,
/// status provided by the router
pub status: String,
/// optional error provided by the router
pub router_error: Option<String>,
/// decision to be taken for auto retries flow
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
#[schema(value_type = GsmDecision)]
pub decision: api_enums::GsmDecision,
/// indicates if step_up retry is possible
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
pub step_up_possible: bool,
/// error code unified across the connectors
pub unified_code: Option<String>,
/// error message unified across the connectors
pub unified_message: Option<String>,
/// category in which error belongs to
#[schema(value_type = Option<ErrorCategory>)]
pub error_category: Option<api_enums::ErrorCategory>,
/// indicates if retry with pan is possible
/// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.
#[schema(deprecated)]
pub clear_pan_possible: bool,
/// Indicates the GSM feature associated with the request,
/// such as retry mechanisms or other specific functionalities provided by the system.
#[schema(value_type = GsmFeature)]
pub feature: api_enums::GsmFeature,
/// Contains the data relevant to the specified GSM feature, if applicable.
/// For example, if the `feature` is `Retry`, this will include configuration
/// details specific to the retry behavior.
#[schema(value_type = GsmFeatureData)]
pub feature_data: Option<common_types::domain::GsmFeatureData>,
/// Code that identifies the specific cause for a failure within a broader error category such as `INVALID_EXPIRY_DATE`, `INVALID_CARD_NUMBER`, or `INSUFFICIENT_FUNDS`.
#[schema(value_type = Option<StandardisedCode>)]
pub standardised_code: Option<api_enums::StandardisedCode>,
/// A detailed description of the error intended for debugging, analytics, and support teams.
pub description: Option<String>,
/// A user-friendly message that can be safely displayed to the customer.
/// This message provides guidance on what the user should do to
/// resolve the issue.
pub user_guidance_message: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/payment_methods.rs | crates/api_models/src/payment_methods.rs | use std::collections::{HashMap, HashSet};
#[cfg(feature = "v2")]
use std::str::FromStr;
use cards::CardNumber;
#[cfg(feature = "v1")]
use common_utils::crypto::OptionalEncryptableName;
use common_utils::{
consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH,
errors,
ext_traits::OptionExt,
id_type, link_utils, pii,
types::{MinorUnit, Percentage, Surcharge},
};
use masking::PeekInterface;
use serde::de;
use utoipa::ToSchema;
#[cfg(feature = "v1")]
use crate::payments::BankCodeResponse;
#[cfg(feature = "payouts")]
use crate::payouts;
use crate::{admin, enums as api_enums, open_router, payments};
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodCreate {
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod,example = "card")]
pub payment_method: Option<api_enums::PaymentMethod>,
/// This is a sub-category of payment method.
#[schema(value_type = Option<PaymentMethodType>,example = "credit")]
pub payment_method_type: Option<api_enums::PaymentMethodType>,
/// The name of the bank/ provider issuing the payment method to the end user
#[schema(example = "Citibank")]
pub payment_method_issuer: Option<String>,
/// A standard code representing the issuer of payment method
#[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")]
pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>,
/// Card Details
#[schema(example = json!({
"card_number": "4111111145551142",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "John Doe"}))]
pub card: Option<CardDetail>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// The unique identifier of the customer.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
/// The card network
#[schema(example = "Visa")]
pub card_network: Option<String>,
/// Payment method details from locker
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Bank>)]
pub bank_transfer: Option<payouts::Bank>,
/// Payment method details from locker
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Wallet>)]
pub wallet: Option<payouts::Wallet>,
/// For Client based calls, SDK will use the client_secret
/// in order to call /payment_methods
/// Client secret will be generated whenever a new
/// payment method is created
pub client_secret: Option<String>,
/// Payment method data to be passed in case of client
/// based flow
pub payment_method_data: Option<PaymentMethodCreateData>,
/// The billing details of the payment method
#[schema(value_type = Option<Address>)]
pub billing: Option<payments::Address>,
#[serde(skip_deserializing)]
/// The connector mandate details of the payment method, this is added only for cards migration
/// api and is skipped during deserialization of the payment method create request as this
/// it should not be passed in the request
pub connector_mandate_details: Option<PaymentsMandateReference>,
#[serde(skip_deserializing)]
/// The transaction id of a CIT (customer initiated transaction) associated with the payment method,
/// this is added only for cards migration api and is skipped during deserialization of the
/// payment method create request as it should not be passed in the request
pub network_transaction_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodCreate {
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod,example = "card")]
pub payment_method_type: api_enums::PaymentMethod,
/// This is a sub-category of payment method.
#[schema(value_type = PaymentMethodType,example = "credit")]
pub payment_method_subtype: api_enums::PaymentMethodType,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// The unique identifier of the customer.
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub customer_id: Option<id_type::GlobalCustomerId>,
/// Payment method data to be passed
pub payment_method_data: PaymentMethodCreateData,
/// The billing details of the payment method
#[schema(value_type = Option<Address>)]
pub billing: Option<payments::Address>,
/// The tokenization type to be applied
#[schema(value_type = Option<PspTokenization>)]
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
/// The network tokenization configuration if applicable
#[schema(value_type = Option<NetworkTokenization>)]
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
/// The storage type for the payment method
#[schema(value_type = Option<StorageType>)]
pub storage_type: Option<common_enums::StorageType>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodIntentCreate {
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// The billing details of the payment method
#[schema(value_type = Option<Address>)]
pub billing: Option<payments::Address>,
/// The unique identifier of the customer.
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub customer_id: id_type::GlobalCustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodIntentConfirm {
/// The unique identifier of the customer.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
/// Payment method data to be passed
pub payment_method_data: PaymentMethodCreateData,
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod,example = "card")]
pub payment_method_type: api_enums::PaymentMethod,
/// This is a sub-category of payment method.
#[schema(value_type = PaymentMethodType,example = "credit")]
pub payment_method_subtype: api_enums::PaymentMethodType,
}
#[cfg(feature = "v2")]
impl PaymentMethodIntentConfirm {
pub fn validate_payment_method_data_against_payment_method(
payment_method_type: api_enums::PaymentMethod,
payment_method_data: PaymentMethodCreateData,
) -> bool {
match payment_method_type {
api_enums::PaymentMethod::Card => {
matches!(
payment_method_data,
PaymentMethodCreateData::Card(_) | PaymentMethodCreateData::ProxyCard(_)
)
}
_ => false,
}
}
}
/// This struct is used internally only
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodIntentConfirmInternal {
pub id: id_type::GlobalPaymentMethodId,
pub request: PaymentMethodIntentConfirm,
}
#[cfg(feature = "v2")]
impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm {
fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
item.request
}
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
/// This struct is only used by and internal api to migrate payment method
pub struct PaymentMethodMigrate {
/// Merchant id
pub merchant_id: id_type::MerchantId,
/// The type of payment method use for the payment.
pub payment_method: Option<api_enums::PaymentMethod>,
/// This is a sub-category of payment method.
pub payment_method_type: Option<api_enums::PaymentMethodType>,
/// The name of the bank/ provider issuing the payment method to the end user
pub payment_method_issuer: Option<String>,
/// A standard code representing the issuer of payment method
pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>,
/// Card Details
pub card: Option<MigrateCardDetail>,
/// Network token details
pub network_token: Option<MigrateNetworkTokenDetail>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
pub metadata: Option<pii::SecretSerdeValue>,
/// The unique identifier of the customer.
pub customer_id: Option<id_type::CustomerId>,
/// The card network
pub card_network: Option<String>,
/// Payment method details from locker
#[cfg(feature = "payouts")]
pub bank_transfer: Option<payouts::Bank>,
/// Payment method details from locker
#[cfg(feature = "payouts")]
pub wallet: Option<payouts::Wallet>,
/// Payment method data to be passed in case of client
/// based flow
pub payment_method_data: Option<PaymentMethodCreateData>,
/// The billing details of the payment method
pub billing: Option<payments::Address>,
/// The connector mandate details of the payment method
#[serde(deserialize_with = "deserialize_connector_mandate_details")]
pub connector_mandate_details: Option<CommonMandateReference>,
// The CIT (customer initiated transaction) transaction id associated with the payment method
pub network_transaction_id: Option<String>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodMigrateResponse {
//payment method response when payment method entry is created
pub payment_method_response: PaymentMethodResponse,
//card data migration status
pub card_migrated: Option<bool>,
//network token data migration status
pub network_token_migrated: Option<bool>,
//connector mandate details migration status
pub connector_mandate_details_migrated: Option<bool>,
//network transaction id migration status
pub network_transaction_id_migrated: Option<bool>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodRecordUpdateResponse {
pub payment_method_id: String,
pub status: common_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub connector_mandate_details: Option<pii::SecretSerdeValue>,
pub updated_payment_method_data: Option<bool>,
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReference(
pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PayoutsMandateReference(
pub HashMap<id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PaymentsMandateReferenceRecord {
pub connector_mandate_id: String,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::Currency>,
pub connector_customer_id: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl From<CommonMandateReference> for PaymentsMandateReference {
fn from(common_mandate: CommonMandateReference) -> Self {
common_mandate.payments.unwrap_or_default()
}
}
impl From<PaymentsMandateReference> for CommonMandateReference {
fn from(payments_reference: PaymentsMandateReference) -> Self {
Self {
payments: Some(payments_reference),
payouts: None,
}
}
}
fn deserialize_connector_mandate_details<'de, D>(
deserializer: D,
) -> Result<Option<CommonMandateReference>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: Option<serde_json::Value> =
<Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?;
let payments_data = value
.clone()
.map(|mut mandate_details| {
mandate_details
.as_object_mut()
.map(|obj| obj.remove("payouts"));
serde_json::from_value::<PaymentsMandateReference>(mandate_details)
})
.transpose()
.map_err(|err| {
let err_msg = format!("{err:?}");
de::Error::custom(format_args!(
"Failed to deserialize PaymentsMandateReference `{err_msg}`",
))
})?;
let payouts_data = value
.clone()
.map(|mandate_details| {
serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map(
|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
},
)
})
.transpose()
.map_err(|err| {
let err_msg = format!("{err:?}");
de::Error::custom(format_args!(
"Failed to deserialize CommonMandateReference `{err_msg}`",
))
})?
.flatten();
Ok(Some(CommonMandateReference {
payments: payments_data,
payouts: payouts_data,
}))
}
#[cfg(feature = "v1")]
impl PaymentMethodCreate {
pub fn get_payment_method_create_from_payment_method_migrate(
card_number: CardNumber,
payment_method_migrate: &PaymentMethodMigrate,
) -> Self {
let card_details =
payment_method_migrate
.card
.as_ref()
.map(|payment_method_migrate_card| CardDetail {
card_number,
card_exp_month: payment_method_migrate_card.card_exp_month.clone(),
card_exp_year: payment_method_migrate_card.card_exp_year.clone(),
card_holder_name: payment_method_migrate_card.card_holder_name.clone(),
nick_name: payment_method_migrate_card.nick_name.clone(),
card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(),
card_issuing_country_code: payment_method_migrate_card
.card_issuing_country_code
.clone(),
card_network: payment_method_migrate_card.card_network.clone(),
card_issuer: payment_method_migrate_card.card_issuer.clone(),
card_type: payment_method_migrate_card.card_type.clone(),
card_cvc: None,
});
Self {
customer_id: payment_method_migrate.customer_id.clone(),
payment_method: payment_method_migrate.payment_method,
payment_method_type: payment_method_migrate.payment_method_type,
payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(),
payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code,
metadata: payment_method_migrate.metadata.clone(),
payment_method_data: payment_method_migrate.payment_method_data.clone(),
connector_mandate_details: payment_method_migrate
.connector_mandate_details
.clone()
.map(|common_mandate_reference| {
PaymentsMandateReference::from(common_mandate_reference)
}),
client_secret: None,
billing: payment_method_migrate.billing.clone(),
card: card_details,
card_network: payment_method_migrate.card_network.clone(),
#[cfg(feature = "payouts")]
bank_transfer: payment_method_migrate.bank_transfer.clone(),
#[cfg(feature = "payouts")]
wallet: payment_method_migrate.wallet.clone(),
network_transaction_id: payment_method_migrate.network_transaction_id.clone(),
}
}
}
#[cfg(feature = "v2")]
impl PaymentMethodCreate {
pub fn validate_payment_method_data_against_payment_method(
payment_method_type: api_enums::PaymentMethod,
payment_method_data: PaymentMethodCreateData,
) -> bool {
match payment_method_type {
api_enums::PaymentMethod::Card => {
matches!(
payment_method_data,
PaymentMethodCreateData::Card(_) | PaymentMethodCreateData::ProxyCard(_)
)
}
_ => false,
}
}
pub fn get_tokenize_connector_id(
&self,
) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>>
{
self.psp_tokenization
.clone()
.get_required_value("psp_tokenization")
.map(|psp| psp.connector_id)
}
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodUpdate {
/// Card Details
#[schema(example = json!({
"card_number": "4111111145551142",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "John Doe"}))]
pub card: Option<CardDetailUpdate>,
/// Wallet Details
pub wallet: Option<PaymentMethodDataWalletInfo>,
/// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
#[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
pub client_secret: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentMethodUpdate {
/// Payment method details to be updated for the payment_method
pub payment_method_data: Option<PaymentMethodUpdateData>,
/// The connector token details to be updated for the payment_method
pub connector_token_details: Option<ConnectorTokenDetails>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodUpdateData {
Card(CardDetailUpdate),
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
ProxyCard(ProxyCardDetails),
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetail {
/// Card Number
#[schema(value_type = String,example = "4111111145551142")]
pub card_number: CardNumber,
/// Card Expiry Month
#[schema(value_type = String,example = "10")]
pub card_exp_month: masking::Secret<String>,
/// Card Expiry Year
#[schema(value_type = String,example = "25")]
pub card_exp_year: masking::Secret<String>,
/// Card CVC for Volatile Storage
#[schema(value_type = Option<String>,example = "123")]
pub card_cvc: Option<masking::Secret<String>>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Issuing Country
pub card_issuing_country: Option<String>,
/// Card Issuing Country Code
pub card_issuing_country_code: Option<String>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<api_enums::CardNetwork>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card Type
pub card_type: Option<String>,
}
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
ToSchema,
strum::EnumString,
strum::Display,
Eq,
PartialEq,
)]
#[serde(rename_all = "snake_case")]
pub enum CardType {
Credit,
Debit,
}
// We cannot use the card struct that we have for payments for the following reason
// The card struct used for payments has card_cvc as mandatory
// but when vaulting the card, we do not need cvc to be collected from the user
// This is because, the vaulted payment method can be used for future transactions in the presence of the customer
// when the customer is on_session again, the cvc can be collected from the customer
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetail {
/// Card Number
#[schema(value_type = String,example = "4111111145551142")]
pub card_number: CardNumber,
/// Card Expiry Month
#[schema(value_type = String,example = "10")]
pub card_exp_month: masking::Secret<String>,
/// Card Expiry Year
#[schema(value_type = String,example = "25")]
pub card_exp_year: masking::Secret<String>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Issuing Country
#[schema(value_type = CountryAlpha2)]
pub card_issuing_country: Option<api_enums::CountryAlpha2>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<api_enums::CardNetwork>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card Type
pub card_type: Option<CardType>,
/// The CVC number for the card
/// This is optional in case the card needs to be vaulted
#[schema(value_type = String, example = "242")]
pub card_cvc: Option<masking::Secret<String>>,
}
// This struct is for collecting Proxy Card Data
// All card related data present in this struct are tokenzied
// No strict type is present to accept tokenized data
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct ProxyCardDetails {
/// Tokenized Card Number
#[schema(value_type = String,example = "tok_sjfowhoejsldj")]
pub card_number: masking::Secret<String>,
/// Card Expiry Month
#[schema(value_type = String,example = "10")]
pub card_exp_month: masking::Secret<String>,
/// Card Expiry Year
#[schema(value_type = String,example = "25")]
pub card_exp_year: masking::Secret<String>,
/// First Six Digit of Card Number
pub bin_number: Option<String>,
///Last Four Digit of Card Number
pub last_four: Option<String>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<common_enums::CardNetwork>,
/// Card Type
pub card_type: Option<String>,
/// Issuing Country of the Card
pub card_issuing_country: Option<String>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// The CVC number for the card
/// This is optional in case the card needs to be vaulted
#[schema(value_type = String, example = "242")]
pub card_cvc: Option<masking::Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MigrateCardDetail {
/// Card Number
#[schema(value_type = String,example = "4111111145551142")]
pub card_number: masking::Secret<String>,
/// Card Expiry Month
#[schema(value_type = String,example = "10")]
pub card_exp_month: masking::Secret<String>,
/// Card Expiry Year
#[schema(value_type = String,example = "25")]
pub card_exp_year: masking::Secret<String>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Issuing Country
pub card_issuing_country: Option<String>,
/// Card Issuing Country Code
pub card_issuing_country_code: Option<String>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<api_enums::CardNetwork>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card Type
pub card_type: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MigrateNetworkTokenData {
/// Network Token Number
#[schema(value_type = String,example = "4111111145551142")]
pub network_token_number: CardNumber,
/// Network Token Expiry Month
#[schema(value_type = String,example = "10")]
pub network_token_exp_month: masking::Secret<String>,
/// Network Token Expiry Year
#[schema(value_type = String,example = "25")]
pub network_token_exp_year: masking::Secret<String>,
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card Issuing Country
pub card_issuing_country: Option<String>,
/// Card Issuing Country
pub card_issuing_country_code: Option<String>,
/// Card's Network
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<api_enums::CardNetwork>,
/// Issuer Bank for Card
pub card_issuer: Option<String>,
/// Card Type
pub card_type: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MigrateNetworkTokenDetail {
/// Network token details
pub network_token_data: MigrateNetworkTokenData,
/// Network token requestor reference id
pub network_token_requestor_ref_id: String,
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetailUpdate {
/// Card Expiry Month
#[schema(value_type = String, example = "10")]
pub card_exp_month: Option<masking::Secret<String>>,
/// Card Expiry Year
#[schema(value_type = String, example = "25")]
pub card_exp_year: Option<masking::Secret<String>>,
/// Card Holder Name
#[schema(value_type = String, example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>, example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
/// Card's Last 4 Digits
#[schema(value_type = Option<String>, example = "1111")]
pub last4_digits: Option<String>,
/// Issuing Bank of the Particular Card
#[schema(value_type = Option<String>, example = "Bank of America")]
pub card_issuer: Option<String>,
/// The country where that particular card was issued
#[schema(value_type = Option<String>, example = "US")]
pub issuer_country: Option<String>,
/// The country code where that particular card was issued
#[schema(value_type = Option<String>, example = "US")]
pub issuer_country_code: Option<String>,
/// The card network
#[schema(value_type = Option<String>, example = "VISA")]
pub card_network: Option<common_enums::CardNetwork>,
}
#[cfg(feature = "v1")]
impl CardDetailUpdate {
pub fn apply(&self, card_data_from_locker: Card) -> CardDetail {
CardDetail {
card_number: card_data_from_locker.card_number,
card_exp_month: self
.card_exp_month
.clone()
.unwrap_or(card_data_from_locker.card_exp_month),
card_exp_year: self
.card_exp_year
.clone()
.unwrap_or(card_data_from_locker.card_exp_year),
card_holder_name: self
.card_holder_name
.clone()
.or(card_data_from_locker.name_on_card),
nick_name: self
.nick_name
.clone()
.or(card_data_from_locker.nick_name.map(masking::Secret::new)),
card_cvc: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_network: None,
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetailUpdate {
/// Card Holder Name
#[schema(value_type = String,example = "John Doe")]
pub card_holder_name: Option<masking::Secret<String>>,
/// Card Holder's Nick Name
#[schema(value_type = Option<String>,example = "John Doe")]
pub nick_name: Option<masking::Secret<String>>,
}
#[cfg(feature = "v2")]
impl CardDetailUpdate {
pub fn apply(&self, card_data_from_locker: Card) -> CardDetail {
CardDetail {
card_number: card_data_from_locker.card_number,
card_exp_month: card_data_from_locker.card_exp_month,
card_exp_year: card_data_from_locker.card_exp_year,
card_holder_name: self
.card_holder_name
.clone()
.or(card_data_from_locker.name_on_card),
nick_name: self
.nick_name
.clone()
.or(card_data_from_locker.nick_name.map(masking::Secret::new)),
card_issuing_country: None,
card_network: None,
card_issuer: None,
card_type: None,
card_cvc: None,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodResponseData {
Card(CardDetailFromLocker),
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponse {
/// Unique identifier for a merchant
#[schema(example = "merchant_1671528864", value_type = String)]
pub merchant_id: id_type::MerchantId,
/// The unique identifier of the customer.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/currency.rs | crates/api_models/src/currency.rs | use common_utils::{events::ApiEventMetric, types::MinorUnit};
/// QueryParams to be send to convert the amount -> from_currency -> to_currency
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CurrencyConversionParams {
pub amount: MinorUnit,
pub to_currency: String,
pub from_currency: String,
}
/// Response to be send for convert currency route
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CurrencyConversionResponse {
pub converted_amount: String,
pub currency: String,
}
impl ApiEventMetric for CurrencyConversionResponse {}
impl ApiEventMetric for CurrencyConversionParams {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/authentication.rs | crates/api_models/src/authentication.rs | use common_enums::{enums, AuthenticationConnectors};
#[cfg(feature = "v1")]
use common_utils::errors::{self, CustomResult};
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
id_type,
};
#[cfg(feature = "v1")]
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
#[cfg(feature = "v1")]
use crate::payments::{Address, BrowserInformation, PaymentMethodData};
use crate::payments::{
ClickToPaySessionResponse, CustomerDetails, DeviceChannel, SdkInformation,
ThreeDsCompletionIndicator,
};
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationCreateRequest {
/// The unique identifier for this authentication.
#[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: Option<id_type::AuthenticationId>,
/// The business profile that is associated with this authentication
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// Customer details.
#[schema(value_type = Option<CustomerDetails>)]
pub customer: Option<CustomerDetails>,
/// The amount for the transaction, required.
#[schema(value_type = MinorUnit, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// The connector to be used for authentication, if known.
#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]
pub authentication_connector: Option<AuthenticationConnectors>,
/// The currency for the transaction, required.
#[schema(value_type = Currency)]
pub currency: common_enums::Currency,
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = Option<String>, example = "https://example.com/redirect")]
pub return_url: Option<String>,
/// Force 3DS challenge.
#[serde(default)]
pub force_3ds_challenge: Option<bool>,
/// Choose what kind of sca exemption is required for this payment
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Profile Acquirer ID get from profile acquirer configuration
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
/// Acquirer details information
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
/// Customer details.
#[schema(value_type = Option<CustomerDetails>)]
pub customer_details: Option<CustomerDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AcquirerDetails {
/// The bin of the card.
#[schema(value_type = Option<String>, example = "123456")]
pub acquirer_bin: Option<String>,
/// The merchant id of the card.
#[schema(value_type = Option<String>, example = "merchant_abc")]
pub acquirer_merchant_id: Option<String>,
/// The country code of the card.
#[schema(value_type = Option<String>, example = "US/34456")]
pub merchant_country_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationResponse {
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
#[schema(value_type = String, example = "merchant_abc")]
pub merchant_id: id_type::MerchantId,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The client secret for this authentication, to be used for client-side operations.
#[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4_secret_el9ksDkiB8hi6j9N78yo")]
pub client_secret: Option<masking::Secret<String>>,
/// The amount for the transaction.
#[schema(value_type = MinorUnit, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// The currency for the transaction.
#[schema(value_type = Currency)]
pub currency: enums::Currency,
/// The connector to be used for authentication, if known.
#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]
pub authentication_connector: Option<AuthenticationConnectors>,
/// Whether 3DS challenge was forced.
pub force_3ds_challenge: Option<bool>,
/// The URL to which the user should be redirected after authentication, if provided.
pub return_url: Option<String>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[schema(example = "E0001")]
pub error_code: Option<String>,
/// If there was an error while calling the connector the error message is received here
#[schema(example = "Failed while verifying the card")]
pub error_message: Option<String>,
/// The business profile that is associated with this payment
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// Choose what kind of sca exemption is required for this payment
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Acquirer details information
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
/// Profile Acquirer ID get from profile acquirer configuration
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
/// Customer details.
#[schema(value_type = Option<CustomerDetails>)]
pub customer_details: Option<CustomerDetails>,
}
impl ApiEventMetric for AuthenticationCreateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.authentication_id
.as_ref()
.map(|id| ApiEventsType::Authentication {
authentication_id: id.clone(),
})
}
}
impl ApiEventMetric for AuthenticationResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationEligibilityCheckRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationEligibilityCheckResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationRetrieveEligibilityCheckRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationRetrieveEligibilityCheckResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationEligibilityRequest {
/// Payment method-specific data such as card details, wallet info, etc.
/// This holds the raw information required to process the payment method.
#[schema(value_type = PaymentMethodData)]
pub payment_method_data: PaymentMethodData,
/// Enum representing the type of payment method being used
/// (e.g., Card, Wallet, UPI, BankTransfer, etc.).
#[schema(value_type = PaymentMethod)]
pub payment_method: common_enums::PaymentMethod,
/// Can be used to specify the Payment Method Type
#[schema(value_type = Option<PaymentMethodType>, example = "debit")]
pub payment_method_type: Option<enums::PaymentMethodType>,
/// Optional secret value used to identify and authorize the client making the request.
/// This can help ensure that the payment session is secure and valid.
#[schema(value_type = Option<String>)]
pub client_secret: Option<masking::Secret<String>>,
/// Optional identifier for the business profile associated with the payment.
/// This determines which configurations, rules, and branding are applied to the transaction.
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// Optional billing address of the customer.
/// This can be used for fraud detection, authentication, or compliance purposes.
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// Optional shipping address of the customer.
/// This can be useful for logistics, verification, or additional risk checks.
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// Optional information about the customer's browser (user-agent, language, etc.).
/// This is typically used to support 3DS authentication flows and improve risk assessment.
#[schema(value_type = Option<BrowserInformation>)]
pub browser_information: Option<BrowserInformation>,
/// Optional email address of the customer.
/// Used for customer identification, communication, and possibly for 3DS or fraud checks.
#[schema(value_type = Option<String>)]
pub email: Option<common_utils::pii::Email>,
}
#[cfg(feature = "v1")]
impl AuthenticationEligibilityRequest {
pub fn get_next_action_api(
&self,
base_url: String,
authentication_id: String,
) -> CustomResult<NextAction, errors::ParsingError> {
let url = format!("{base_url}/authentication/{authentication_id}/authenticate");
Ok(NextAction {
url: url::Url::parse(&url).change_context(errors::ParsingError::UrlParsingError)?,
http_method: common_utils::request::Method::Post,
})
}
pub fn get_billing_address(&self) -> Option<Address> {
self.billing.clone()
}
pub fn get_shipping_address(&self) -> Option<Address> {
self.shipping.clone()
}
pub fn get_browser_information(&self) -> Option<BrowserInformation> {
self.browser_information.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, ToSchema)]
pub struct AuthenticationEligibilityResponse {
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = NextAction)]
pub next_action: NextAction,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The 3DS data for this authentication.
#[schema(value_type = Option<EligibilityResponseParams>)]
pub eligibility_response_params: Option<EligibilityResponseParams>,
/// The metadata for this authentication.
#[schema(value_type = serde_json::Value)]
pub connector_metadata: Option<serde_json::Value>,
/// The unique identifier for this authentication.
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// The error message for this authentication.
#[schema(value_type = Option<String>)]
pub error_message: Option<String>,
/// The error code for this authentication.
#[schema(value_type = Option<String>)]
pub error_code: Option<String>,
/// The connector used for this authentication.
#[schema(value_type = Option<AuthenticationConnectors>)]
pub authentication_connector: Option<AuthenticationConnectors>,
/// Billing address
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// Shipping address
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// Browser information
#[schema(value_type = Option<BrowserInformation>)]
pub browser_information: Option<BrowserInformation>,
/// Email
#[schema(value_type = Option<String>)]
pub email: common_utils::crypto::OptionalEncryptableEmail,
/// Acquirer details information.
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationEligibilityCheckRequest {
/// The unique identifier for this authentication.
/// Added in the request for api event metrics, populated from path parameter
#[serde(skip)]
pub authentication_id: id_type::AuthenticationId,
/// Optional secret value used to identify and authorize the client making the request.
/// This can help ensure that the payment session is secure and valid.
#[schema(value_type = Option<String>)]
pub client_secret: Option<masking::Secret<String>>,
/// The data for this authentication eligibility check.
pub eligibility_check_data: AuthenticationEligibilityCheckData,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, ToSchema)]
pub struct AuthenticationEligibilityCheckResponse {
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
// The next action for this authentication eligibility check.
pub sdk_next_action: AuthenticationSdkNextAction,
}
#[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum AuthenticationSdkNextAction {
/// The next action is to await for a merchant callback
AwaitMerchantCallback,
/// The next action is to deny the payment with an error message
Deny { message: String },
/// The next action is to proceed with the payment
Proceed,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationRetrieveEligibilityCheckRequest {
/// The unique identifier for this authentication.
/// Added in the request for api event metrics, populated from path parameter
#[serde(skip)]
pub authentication_id: id_type::AuthenticationId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationRetrieveEligibilityCheckResponse {
/// The unique identifier for this authentication.
/// Added in the request for api event metrics, populated from path parameter
#[serde(skip)]
pub authentication_id: id_type::AuthenticationId,
/// The data for this authentication eligibility check.
pub eligibility_check_data: AuthenticationEligibilityCheckResponseData,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum AuthenticationEligibilityCheckData {
ClickToPay(ClickToPayEligibilityCheckData),
}
#[cfg(feature = "v1")]
impl AuthenticationEligibilityCheckData {
pub fn get_click_to_pay_data(&self) -> Option<&ClickToPayEligibilityCheckData> {
match self {
Self::ClickToPay(data) => Some(data),
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum AuthenticationEligibilityCheckResponseData {
ClickToPayEnrollmentStatus(ClickToPayEligibilityCheckResponseData),
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct ClickToPayEligibilityCheckData {
// Visa specific eligibility check data
pub visa: Option<VisaEligibilityCheckData>,
// MasterCard specific eligibility check data
pub mastercard: Option<MasterCardEligibilityCheckData>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct ClickToPayEligibilityCheckResponseData {
// Visa specific eligibility check data
pub visa: Option<bool>,
// MasterCard specific eligibility check data
pub mastercard: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct VisaEligibilityCheckData {
// Indicates whether the consumer is enrolled in Visa Secure program
pub consumer_present: bool,
// Status of the consumer in Visa Secure program]
#[serde(skip_serializing_if = "Option::is_none")]
pub consumer_status: Option<String>,
// Additional data for eligibility check
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<BrowserInformation>)]
pub custom_data: Option<common_utils::pii::SecretSerdeValue>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct MasterCardEligibilityCheckData {
// Indicates whether the consumer is enrolled in MasterCard Identity Check program
pub consumer_present: bool,
// Session ID from MasterCard Identity Check program
#[serde(skip_serializing_if = "Option::is_none")]
pub id_lookup_session_id: Option<String>,
// Timestamp of the last time the card was used
#[serde(skip_serializing_if = "Option::is_none")]
pub last_used_card_timestamp: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub enum EligibilityResponseParams {
ThreeDsData(ThreeDsData),
}
#[derive(Debug, Serialize, ToSchema)]
pub struct ThreeDsData {
/// The unique identifier for this authentication from the 3DS server.
#[schema(value_type = String)]
pub three_ds_server_transaction_id: Option<String>,
/// The maximum supported 3DS version.
#[schema(value_type = String)]
pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>,
/// The unique identifier for this authentication from the connector.
#[schema(value_type = String)]
pub connector_authentication_id: Option<String>,
/// The data required to perform the 3DS method.
#[schema(value_type = String)]
pub three_ds_method_data: Option<String>,
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = String, example = "https://example.com/redirect")]
pub three_ds_method_url: Option<url::Url>,
/// The version of the message.
#[schema(value_type = String)]
pub message_version: Option<common_utils::types::SemanticVersion>,
/// The unique identifier for this authentication.
#[schema(value_type = String)]
pub directory_server_id: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct NextAction {
/// The URL for authenticatating the user.
#[schema(value_type = String)]
pub url: url::Url,
/// The HTTP method to use for the request.
#[schema(value_type = Method)]
pub http_method: common_utils::request::Method,
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationEligibilityRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationEligibilityResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationAuthenticateRequest {
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
/// Client secret for the authentication
#[schema(value_type = String)]
pub client_secret: Option<masking::Secret<String>>,
/// SDK Information if request is from SDK
pub sdk_information: Option<SdkInformation>,
/// Device Channel indicating whether request is coming from App or Browser
pub device_channel: DeviceChannel,
/// Indicates if 3DS method data was successfully completed or not
pub threeds_method_comp_ind: ThreeDsCompletionIndicator,
}
impl ApiEventMetric for AuthenticationAuthenticateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationAuthenticateResponse {
/// Indicates the transaction status
#[serde(rename = "trans_status")]
#[schema(value_type = Option<TransactionStatus>)]
pub transaction_status: Option<common_enums::TransactionStatus>,
/// Access Server URL to be used for challenge submission
#[schema(value_type = String, example = "https://example.com/redirect")]
pub acs_url: Option<url::Url>,
/// Challenge request which should be sent to acs_url
pub challenge_request: Option<String>,
/// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa)
pub acs_reference_number: Option<String>,
/// Unique identifier assigned by the ACS to identify a single transaction
pub acs_trans_id: Option<String>,
/// Unique identifier assigned by the 3DS Server to identify a single transaction
pub three_ds_server_transaction_id: Option<String>,
/// Contains the JWS object created by the ACS for the ARes(Authentication Response) message
pub acs_signed_content: Option<String>,
/// Three DS Requestor URL
pub three_ds_requestor_url: String,
/// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred
pub three_ds_requestor_app_url: Option<String>,
/// The error message for this authentication.
#[schema(value_type = String)]
pub error_message: Option<String>,
/// The error code for this authentication.
#[schema(value_type = String)]
pub error_code: Option<String>,
/// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.
#[schema(value_type = String)]
pub authentication_value: Option<masking::Secret<String>>,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The connector to be used for authentication, if known.
#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]
pub authentication_connector: Option<AuthenticationConnectors>,
/// The unique identifier for this authentication.
#[schema(value_type = AuthenticationId, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// The ECI value for this authentication.
#[schema(value_type = String)]
pub eci: Option<String>,
/// Acquirer details information.
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
}
impl ApiEventMetric for AuthenticationAuthenticateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuthenticationSyncResponse {
// Core Authentication Fields (from AuthenticationResponse)
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// This is an identifier for the merchant account.
#[schema(value_type = String, example = "merchant_abc")]
pub merchant_id: id_type::MerchantId,
/// The current status of the authentication.
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The client secret for this authentication.
#[schema(value_type = Option<String>)]
pub client_secret: Option<masking::Secret<String>>,
/// The amount for the transaction.
#[schema(value_type = MinorUnit, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// The currency for the transaction.
#[schema(value_type = Currency)]
pub currency: enums::Currency,
/// The connector used for authentication.
#[schema(value_type = Option<AuthenticationConnectors>)]
pub authentication_connector: Option<AuthenticationConnectors>,
/// Whether 3DS challenge was forced.
pub force_3ds_challenge: Option<bool>,
/// The URL to which the user should be redirected after authentication.
pub return_url: Option<String>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The business profile that is associated with this authentication.
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// SCA exemption type for this authentication.
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Acquirer details information.
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
/// The unique identifier from the 3DS server.
#[schema(value_type = Option<String>)]
pub threeds_server_transaction_id: Option<String>,
/// The maximum supported 3DS version.
#[schema(value_type = Option<String>)]
pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>,
/// The unique identifier from the connector.
#[schema(value_type = Option<String>)]
pub connector_authentication_id: Option<String>,
/// The data required to perform the 3DS method.
#[schema(value_type = Option<String>)]
pub three_ds_method_data: Option<String>,
/// The URL for the 3DS method.
#[schema(value_type = Option<String>)]
pub three_ds_method_url: Option<String>,
/// The version of the message.
#[schema(value_type = Option<String>)]
pub message_version: Option<common_utils::types::SemanticVersion>,
/// The metadata for this authentication.
#[schema(value_type = Option<serde_json::Value>)]
pub connector_metadata: Option<serde_json::Value>,
/// The unique identifier for the directory server.
#[schema(value_type = Option<String>)]
pub directory_server_id: Option<String>,
/// The insensitive payment method data
pub payment_method_data: Option<AuthenticationPaymentMethodDataResponse>,
/// The tokens for vaulted data
pub vault_token_data: Option<AuthenticationVaultTokenData>,
/// Billing address.
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// Shipping address.
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// Browser information.
#[schema(value_type = Option<BrowserInformation>)]
pub browser_information: Option<BrowserInformation>,
/// Email.
#[schema(value_type = Option<String>)]
pub email: common_utils::crypto::OptionalEncryptableEmail,
/// Indicates the transaction status.
#[serde(rename = "trans_status")]
#[schema(value_type = Option<TransactionStatus>)]
pub transaction_status: Option<common_enums::TransactionStatus>,
/// Access Server URL for challenge submission.
pub acs_url: Option<String>,
/// Challenge request to be sent to acs_url.
pub challenge_request: Option<String>,
/// Unique identifier assigned by EMVCo.
pub acs_reference_number: Option<String>,
/// Unique identifier assigned by the ACS.
pub acs_trans_id: Option<String>,
/// JWS object created by the ACS for the ARes message.
pub acs_signed_content: Option<String>,
/// Three DS Requestor URL.
pub three_ds_requestor_url: Option<String>,
/// Merchant app URL for OOB authentication.
pub three_ds_requestor_app_url: Option<String>,
/// ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.
pub eci: Option<String>,
// Common Error Fields (present in multiple responses)
/// Error message if any.
#[schema(value_type = Option<String>)]
pub error_message: Option<String>,
/// Error code if any.
#[schema(value_type = Option<String>)]
pub error_code: Option<String>,
/// Profile Acquirer ID
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthenticationPaymentMethodDataResponse {
CardData {
/// card expiry year
#[schema(value_type = Option<String>)]
card_expiry_year: Option<masking::Secret<String>>,
/// card expiry month
#[schema(value_type = Option<String>)]
card_expiry_month: Option<masking::Secret<String>>,
},
NetworkTokenData {
/// network token expiry month
#[schema(value_type = Option<String>)]
network_token_expiry_month: Option<masking::Secret<String>>,
/// network token expiry year
#[schema(value_type = Option<String>)]
network_token_expiry_year: Option<masking::Secret<String>>,
},
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthenticationVaultTokenData {
CardData {
/// token representing card_number
#[schema(value_type = Option<String>)]
#[serde(rename = "card_number")]
tokenized_card_number: Option<masking::Secret<String>>,
/// token representing card_expiry_year
#[schema(value_type = Option<String>)]
#[serde(rename = "card_expiry_year")]
tokenized_card_expiry_year: Option<masking::Secret<String>>,
/// token representing card_expiry_month
#[schema(value_type = Option<String>)]
#[serde(rename = "card_expiry_month")]
tokenized_card_expiry_month: Option<masking::Secret<String>>,
/// token representing card_cvc
#[schema(value_type = Option<String>)]
#[serde(rename = "card_cvc")]
tokenized_card_cvc: Option<masking::Secret<String>>,
},
NetworkTokenData {
/// token representing payment_token
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token")]
tokenized_network_token: Option<masking::Secret<String>>,
/// token representing token_expiry_year
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token_expiry_year")]
tokenized_expiry_year: Option<masking::Secret<String>>,
/// token representing token_expiry_month
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token_expiry_month")]
tokenized_expiry_month: Option<masking::Secret<String>>,
/// token representing token_cryptogram
#[schema(value_type = Option<String>)]
#[serde(rename = "network_token_cryptogram")]
tokenized_cryptogram: Option<masking::Secret<String>>,
},
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationSyncResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationSyncRequest {
/// The client secret for this authentication.
#[schema(value_type = String)]
pub client_secret: Option<masking::Secret<String>>,
/// Payment method data for Post Authentication sync
pub payment_method_details: Option<PostAuthenticationRequestPaymentMethodData>,
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/files.rs | crates/api_models/src/files.rs | use utoipa::ToSchema;
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct CreateFileResponse {
/// ID of the file created
pub file_id: String,
}
#[derive(Debug, serde::Serialize, ToSchema, Clone)]
pub struct FileMetadataResponse {
/// ID of the file created
pub file_id: String,
/// Name of the file
pub file_name: Option<String>,
/// Size of the file
pub file_size: i32,
/// Type of the file
pub file_type: String,
/// File availability
pub available: bool,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct FileRetrieveQuery {
///Dispute Id
pub dispute_id: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events.rs | crates/api_models/src/events.rs | pub mod apple_pay_certificates_migration;
pub mod chat;
pub mod connector_onboarding;
pub mod customer;
pub mod dispute;
pub mod external_service_auth;
pub mod gsm;
mod locker_migration;
pub mod payment;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(feature = "recon")]
pub mod recon;
pub mod refund;
#[cfg(feature = "v2")]
pub mod revenue_recovery;
pub mod routing;
pub mod user;
pub mod user_role;
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
impl_api_event_type,
};
use crate::customers::CustomerListRequest;
#[cfg(feature = "tokenization_v2")]
use crate::tokenization;
#[allow(unused_imports)]
use crate::{
admin::*,
analytics::{
api_event::*, auth_events::*, connector_events::ConnectorEventsRequest,
outgoing_webhook_event::OutgoingWebhookLogsRequest, routing_events::RoutingEventsRequest,
sdk_events::*, search::*, *,
},
api_keys::*,
cards_info::*,
disputes::*,
files::*,
mandates::*,
organization::{
OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
},
payment_methods::*,
payments::*,
user::{UserKeyTransferRequest, UserTransferKeyResponse},
verifications::*,
};
impl ApiEventMetric for GetPaymentIntentFiltersRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Analytics)
}
}
impl ApiEventMetric for GetPaymentIntentMetricRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Analytics)
}
}
impl ApiEventMetric for PaymentIntentFiltersResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Analytics)
}
}
impl_api_event_type!(
Miscellaneous,
(
PaymentMethodId,
PaymentMethodCreate,
PaymentLinkInitiateRequest,
RetrievePaymentLinkResponse,
MandateListConstraints,
CreateFileResponse,
MerchantConnectorResponse,
MerchantConnectorId,
MandateResponse,
MandateRevokedResponse,
RetrievePaymentLinkRequest,
PaymentLinkListConstraints,
MandateId,
DisputeListGetConstraints,
RetrieveApiKeyResponse,
ProfileResponse,
ProfileUpdate,
ProfileCreate,
RevokeApiKeyResponse,
ToggleKVResponse,
ToggleKVRequest,
ToggleAllKVRequest,
ToggleAllKVResponse,
MerchantAccountDeleteResponse,
MerchantAccountUpdate,
CardInfoResponse,
CreateApiKeyResponse,
CreateApiKeyRequest,
ListApiKeyConstraints,
MerchantConnectorDeleteResponse,
MerchantConnectorUpdate,
MerchantConnectorCreate,
MerchantId,
CardsInfoRequest,
MerchantAccountResponse,
MerchantAccountListRequest,
MerchantAccountCreate,
PaymentsSessionRequest,
ApplepayMerchantVerificationRequest,
ApplepayMerchantResponse,
ApplepayVerifiedDomainsResponse,
UpdateApiKeyRequest,
GetApiEventFiltersRequest,
ApiEventFiltersResponse,
GetInfoResponse,
GetPaymentMetricRequest,
GetRefundMetricRequest,
GetActivePaymentsMetricRequest,
GetSdkEventMetricRequest,
GetAuthEventMetricRequest,
GetAuthEventFilterRequest,
GetPaymentFiltersRequest,
PaymentFiltersResponse,
GetRefundFilterRequest,
RefundFiltersResponse,
AuthEventFiltersResponse,
GetSdkEventFiltersRequest,
SdkEventFiltersResponse,
ApiLogsRequest,
GetApiEventMetricRequest,
SdkEventsRequest,
ReportRequest,
ConnectorEventsRequest,
OutgoingWebhookLogsRequest,
GetGlobalSearchRequest,
GetSearchRequest,
GetSearchResponse,
GetSearchRequestWithIndex,
GetDisputeFilterRequest,
DisputeFiltersResponse,
GetDisputeMetricRequest,
SankeyResponse,
OrganizationResponse,
OrganizationCreateRequest,
OrganizationUpdateRequest,
OrganizationId,
CustomerListRequest,
RoutingEventsRequest
)
);
impl_api_event_type!(
Keymanager,
(
TransferKeyResponse,
MerchantKeyTransferRequest,
UserKeyTransferRequest,
UserTransferKeyResponse
)
);
impl<T> ApiEventMetric for MetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
impl<T> ApiEventMetric for PaymentsMetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
impl<T> ApiEventMetric for RefundsMetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
impl<T> ApiEventMetric for DisputesMetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
impl<T> ApiEventMetric for AuthEventMetricsResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: Some(self.request.payment_method_type),
payment_method_subtype: Some(self.request.payment_method_subtype),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodIntentCreate {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodCreate)
}
}
impl ApiEventMetric for DisputeListFilters {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodSessionRequest {}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodsSessionUpdateRequest {}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodSessionResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodSession {
payment_method_session_id: self.id.clone(),
})
}
}
#[cfg(feature = "tokenization_v2")]
impl ApiEventMetric for tokenization::GenericTokenizationRequest {}
#[cfg(feature = "tokenization_v2")]
impl ApiEventMetric for tokenization::GenericTokenizationResponse {}
#[cfg(feature = "tokenization_v2")]
impl ApiEventMetric for tokenization::DeleteTokenDataResponse {}
#[cfg(feature = "tokenization_v2")]
impl ApiEventMetric for tokenization::DeleteTokenDataRequest {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/recon.rs | crates/api_models/src/recon.rs | use common_utils::{id_type, pii};
use masking::Secret;
use crate::enums;
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct ReconUpdateMerchantRequest {
pub recon_status: enums::ReconStatus,
pub user_email: pii::Email,
}
#[derive(Debug, serde::Serialize)]
pub struct ReconTokenResponse {
pub token: Secret<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct ReconStatusResponse {
pub recon_status: enums::ReconStatus,
}
#[derive(serde::Serialize, Debug)]
pub struct VerifyTokenResponse {
pub merchant_id: id_type::MerchantId,
pub user_email: pii::Email,
#[serde(skip_serializing_if = "Option::is_none")]
pub acl: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/locker_migration.rs | crates/api_models/src/locker_migration.rs | #[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MigrateCardResponse {
pub status_message: String,
pub status_code: String,
pub customers_moved: usize,
pub cards_moved: usize,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/proxy.rs | crates/api_models/src/proxy.rs | use std::collections::HashMap;
use common_utils::request::Method;
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use utoipa::ToSchema;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Headers(pub HashMap<String, String>);
impl Headers {
pub fn as_map(&self) -> &HashMap<String, String> {
&self.0
}
pub fn from_header_map(headers: Option<&HeaderMap>) -> Self {
headers
.map(|h| {
let map = h
.iter()
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
.collect();
Self(map)
})
.unwrap_or_else(|| Self(HashMap::new()))
}
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct ProxyRequest {
/// The request body that needs to be forwarded
pub request_body: Value,
/// The destination URL where the request needs to be forwarded
#[schema(value_type = String, example = "https://api.example.com/endpoint")]
pub destination_url: url::Url,
/// The headers that need to be forwarded
#[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub headers: Headers,
/// The method that needs to be used for the request
#[schema(value_type = Method, example = "Post")]
pub method: Method,
/// The vault token that is used to fetch sensitive data from the vault
pub token: String,
/// The type of token that is used to fetch sensitive data from the vault
#[schema(value_type = TokenType, example = "payment_method_id")]
pub token_type: TokenType,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenType {
TokenizationId,
PaymentMethodId,
VolatilePaymentMethodId,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct ProxyResponse {
/// The response received from the destination
pub response: Value,
/// The status code of the response
pub status_code: u16,
/// The headers of the response
#[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub response_headers: Headers,
}
impl common_utils::events::ApiEventMetric for ProxyRequest {}
impl common_utils::events::ApiEventMetric for ProxyResponse {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/surcharge_decision_configs.rs | crates/api_models/src/surcharge_decision_configs.rs | use common_utils::{
consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH,
events,
types::{MinorUnit, Percentage},
};
use euclid::frontend::{
ast::Program,
dir::{DirKeyKind, EuclidDirFilter},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct SurchargeDetailsOutput {
pub surcharge: SurchargeOutput,
pub tax_on_surcharge: Option<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum SurchargeOutput {
Fixed { amount: MinorUnit },
Rate(Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>),
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct SurchargeDecisionConfigs {
pub surcharge_details: Option<SurchargeDetailsOutput>,
}
impl EuclidDirFilter for SurchargeDecisionConfigs {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::BillingCountry,
DirKeyKind::CardNetwork,
DirKeyKind::PayLaterType,
DirKeyKind::WalletType,
DirKeyKind::BankTransferType,
DirKeyKind::BankRedirectType,
DirKeyKind::BankDebitType,
DirKeyKind::CryptoType,
DirKeyKind::RealTimePaymentType,
];
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SurchargeDecisionManagerRecord {
pub name: String,
pub merchant_surcharge_configs: MerchantSurchargeConfigs,
pub algorithm: Program<SurchargeDecisionConfigs>,
pub created_at: i64,
pub modified_at: i64,
}
impl events::ApiEventMetric for SurchargeDecisionManagerRecord {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SurchargeDecisionConfigReq {
pub name: Option<String>,
pub merchant_surcharge_configs: MerchantSurchargeConfigs,
pub algorithm: Option<Program<SurchargeDecisionConfigs>>,
}
impl events::ApiEventMetric for SurchargeDecisionConfigReq {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct MerchantSurchargeConfigs {
pub show_surcharge_breakup_screen: Option<bool>,
}
pub type SurchargeDecisionManagerResponse = SurchargeDecisionManagerRecord;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/payments.rs | crates/api_models/src/payments.rs | #[cfg(feature = "v1")]
use std::fmt;
use std::{
collections::{HashMap, HashSet},
num::NonZeroI64,
};
pub mod additional_info;
pub mod trait_impls;
use cards::{CardNumber, NetworkToken};
#[cfg(feature = "v2")]
use common_enums::enums::PaymentConnectorTransmission;
use common_enums::{GooglePayCardFundingSource, ProductType};
#[cfg(feature = "v1")]
use common_types::primitive_wrappers::{
ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool,
};
use common_types::{payments as common_payments_types, primitive_wrappers};
use common_utils::{
consts::default_payments_list_limit,
crypto,
errors::ValidationError,
ext_traits::{ConfigExt, Encode, ValueExt},
hashing::HashedString,
id_type,
new_type::MaskedBankAccount,
pii::{self, Email},
types::{AmountConvertor, MinorUnit, SemanticVersion, StringMajorUnit},
};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>
where
D: serde::Deserializer<'de>,
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
let opt_str: Option<String> = Option::deserialize(v)?;
match opt_str {
Some(s) if s.is_empty() => Ok(None),
Some(s) => {
// Estimate capacity based on comma count
let capacity = s.matches(',').count() + 1;
let mut result = Vec::with_capacity(capacity);
for item in s.split(',') {
let trimmed_item = item.trim();
if !trimmed_item.is_empty() {
let parsed_item = trimmed_item.parse::<T>().map_err(|e| {
<D::Error as serde::de::Error>::custom(format!(
"Invalid value '{trimmed_item}': {e}"
))
})?;
result.push(parsed_item);
}
}
Ok(Some(result))
}
None => Ok(None),
}
}
use masking::{PeekInterface, Secret, WithType};
use router_derive::Setter;
#[cfg(feature = "v1")]
use serde::{de, Deserializer};
use serde::{ser::Serializer, Deserialize, Serialize};
use smithy::SmithyModel;
use strum::Display;
use time::{Date, PrimitiveDateTime};
use url::Url;
use utoipa::ToSchema;
#[cfg(feature = "v2")]
use crate::mandates;
use crate::{
admin::{self, MerchantConnectorInfo},
enums as api_enums,
mandates::RecurringDetails,
payment_methods,
payments::additional_info::{
BankDebitAdditionalData, BankRedirectDetails, BankTransferAdditionalData,
CardTokenAdditionalData, GiftCardAdditionalData, UpiAdditionalData,
WalletAdditionalDataForCard,
},
};
#[cfg(feature = "v1")]
use crate::{disputes, refunds, ValidateFieldAndGet};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PaymentOp {
Create,
Update,
Confirm,
}
use crate::enums;
#[derive(serde::Deserialize)]
pub struct BankData {
pub payment_method_type: api_enums::PaymentMethodType,
pub code_information: Vec<BankCodeInformation>,
}
#[derive(serde::Deserialize)]
pub struct BankCodeInformation {
pub bank_name: common_enums::BankNames,
pub connector_codes: Vec<ConnectorCode>,
}
#[derive(serde::Deserialize)]
pub struct ConnectorCode {
pub connector: api_enums::Connector,
pub code: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
pub struct BankCodeResponse {
#[schema(value_type = Vec<BankNames>)]
pub bank_name: Vec<common_enums::BankNames>,
pub eligible_connectors: Vec<String>,
}
/// Passing this object creates a new customer or attaches an existing customer to the payment
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerDetails {
/// The identifier for the customer.
#[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
#[smithy(value_type = "String")]
pub id: id_type::CustomerId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
#[smithy(value_type = "Option<String>")]
pub email: Option<Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 10, example = "9123456789")]
#[smithy(value_type = "Option<String>")]
pub phone: Option<Secret<String>>,
/// The country code for the customer's phone number
#[schema(max_length = 2, example = "+1")]
#[smithy(value_type = "Option<String>")]
pub phone_country_code: Option<String>,
/// The tax registration identifier of the customer.
#[schema(value_type=Option<String>,max_length = 255)]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
/// Details of customer attached to this payment
#[derive(
Debug,
Default,
serde::Serialize,
serde::Deserialize,
Clone,
ToSchema,
PartialEq,
Setter,
SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerDetailsResponse {
/// The identifier for the customer.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
#[smithy(value_type = "Option<String>")]
pub id: Option<id_type::CustomerId>,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
#[smithy(value_type = "Option<String>")]
pub email: Option<Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 10, example = "9123456789")]
#[smithy(value_type = "Option<String>")]
pub phone: Option<Secret<String>>,
/// The country code for the customer's phone number
#[schema(max_length = 2, example = "+1")]
#[smithy(value_type = "Option<String>")]
pub phone_country_code: Option<String>,
}
#[cfg(feature = "v2")]
/// Details of customer attached to this payment
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)]
pub struct CustomerDetailsResponse {
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "John Doe")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
pub email: Option<Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 10, example = "9123456789")]
pub phone: Option<Secret<String>>,
/// The country code for the customer's phone number
#[schema(max_length = 2, example = "+1")]
pub phone_country_code: Option<String>,
}
// Serialize is required because the api event requires Serialize to be implemented
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[cfg(feature = "v2")]
pub struct PaymentsCreateIntentRequest {
/// The amount details for the payment
pub amount_details: AmountDetails,
/// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant.
#[schema(
value_type = Option<String>,
min_length = 30,
max_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4"
)]
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The routing algorithm id to be used for the payment
#[schema(value_type = Option<String>)]
pub routing_algorithm_id: Option<id_type::RoutingId>,
#[schema(value_type = Option<CaptureMethod>, example = "automatic")]
pub capture_method: Option<api_enums::CaptureMethod>,
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")]
pub authentication_type: Option<api_enums::AuthenticationType>,
/// The billing details of the payment. This address will be used for invoicing.
pub billing: Option<Address>,
/// The shipping address for the payment
pub shipping: Option<Address>,
/// The identifier for the customer
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub customer_id: Option<id_type::GlobalCustomerId>,
/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
#[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)]
pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
/// A description for the payment
#[schema(example = "It's my first payment request", value_type = Option<String>)]
pub description: Option<common_utils::types::Description>,
/// The URL to which you want the user to be redirected after the completion of the payment operation
#[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
pub return_url: Option<common_utils::types::Url>,
#[schema(value_type = Option<FutureUsage>, example = "off_session")]
pub setup_future_usage: Option<api_enums::FutureUsage>,
/// Apply MIT exemption for a payment
#[schema(value_type = Option<MitExemptionRequest>)]
pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>,
/// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
#[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)]
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
/// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
#[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount" : 69000
"product_img_link" : "https://dummy-img-link.com"
}]"#)]
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
/// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
#[schema(value_type = Option<Vec<PaymentMethodType>>)]
pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
pub connector_metadata: Option<ConnectorMetadata>,
/// Additional data that might be required by hyperswitch based on the requested features by the merchants.
pub feature_metadata: Option<FeatureMetadata>,
/// Whether to generate the payment link for this payment or not (if applicable)
#[schema(value_type = Option<EnablePaymentLinkRequest>)]
pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>,
/// Configure a custom payment link for the particular payment
#[schema(value_type = Option<PaymentLinkConfigRequest>)]
pub payment_link_config: Option<admin::PaymentLinkConfigRequest>,
///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.
#[schema(value_type = Option<RequestIncrementalAuthorization>)]
pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>,
///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config
///(900) for 15 mins
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Additional data related to some frm(Fraud Risk Management) connectors
#[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// Whether to perform external authentication (if applicable)
#[schema(value_type = Option<External3dsAuthenticationRequest>)]
pub request_external_three_ds_authentication:
Option<common_enums::External3dsAuthenticationRequest>,
/// Indicates if 3ds challenge is forced
pub force_3ds_challenge: Option<bool>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorAuthDetails>)]
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
/// Allow partial authorization for this payment
#[schema(value_type = Option<bool>, default = false)]
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct PaymentAttemptListRequest {
#[schema(value_type = String)]
pub payment_intent_id: id_type::GlobalPaymentId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PaymentAttemptListResponse {
pub payment_attempt_list: Vec<PaymentAttemptResponse>,
}
#[cfg(feature = "v2")]
impl PaymentsCreateIntentRequest {
pub fn get_feature_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<pii::SecretSerdeValue>,
common_utils::errors::ParsingError,
> {
Ok(self
.feature_metadata
.as_ref()
.map(Encode::encode_to_value)
.transpose()?
.map(Secret::new))
}
pub fn get_connector_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<pii::SecretSerdeValue>,
common_utils::errors::ParsingError,
> {
Ok(self
.connector_metadata
.as_ref()
.map(Encode::encode_to_value)
.transpose()?
.map(Secret::new))
}
pub fn get_allowed_payment_method_types_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<pii::SecretSerdeValue>,
common_utils::errors::ParsingError,
> {
Ok(self
.allowed_payment_method_types
.as_ref()
.map(Encode::encode_to_value)
.transpose()?
.map(Secret::new))
}
pub fn get_order_details_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<Vec<pii::SecretSerdeValue>>,
common_utils::errors::ParsingError,
> {
self.order_details
.as_ref()
.map(|od| {
od.iter()
.map(|order| order.encode_to_value().map(Secret::new))
.collect::<Result<Vec<_>, _>>()
})
.transpose()
}
}
// This struct is only used internally, not visible in API Reference
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[cfg(feature = "v2")]
pub struct PaymentsGetIntentRequest {
pub id: id_type::GlobalPaymentId,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[cfg(feature = "v2")]
pub struct PaymentsUpdateIntentRequest {
pub amount_details: Option<AmountDetailsUpdate>,
/// The routing algorithm id to be used for the payment
#[schema(value_type = Option<String>)]
pub routing_algorithm_id: Option<id_type::RoutingId>,
#[schema(value_type = Option<CaptureMethod>, example = "automatic")]
pub capture_method: Option<api_enums::CaptureMethod>,
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")]
pub authentication_type: Option<api_enums::AuthenticationType>,
/// The billing details of the payment. This address will be used for invoicing.
pub billing: Option<Address>,
/// The shipping address for the payment
pub shipping: Option<Address>,
/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
#[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)]
pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
/// A description for the payment
#[schema(example = "It's my first payment request", value_type = Option<String>)]
pub description: Option<common_utils::types::Description>,
/// The URL to which you want the user to be redirected after the completion of the payment operation
#[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
pub return_url: Option<common_utils::types::Url>,
#[schema(value_type = Option<FutureUsage>, example = "off_session")]
pub setup_future_usage: Option<api_enums::FutureUsage>,
/// Apply MIT exemption for a payment
#[schema(value_type = Option<MitExemptionRequest>)]
pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>,
/// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
#[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)]
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
/// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
#[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount" : 69000
"product_img_link" : "https://dummy-img-link.com"
}]"#)]
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
/// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
#[schema(value_type = Option<Vec<PaymentMethodType>>)]
pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
/// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
#[schema(value_type = Option<ConnectorMetadata>)]
pub connector_metadata: Option<ConnectorMetadata>,
/// Additional data that might be required by hyperswitch based on the requested features by the merchants.
#[schema(value_type = Option<FeatureMetadata>)]
pub feature_metadata: Option<FeatureMetadata>,
/// Configure a custom payment link for the particular payment
#[schema(value_type = Option<PaymentLinkConfigRequest>)]
pub payment_link_config: Option<admin::PaymentLinkConfigRequest>,
/// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.
#[schema(value_type = Option<RequestIncrementalAuthorization>)]
pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>,
/// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config
///(900) for 15 mins
#[schema(value_type = Option<u32>, example = 900)]
pub session_expiry: Option<u32>,
/// Additional data related to some frm(Fraud Risk Management) connectors
#[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// Whether to perform external authentication (if applicable)
#[schema(value_type = Option<External3dsAuthenticationRequest>)]
pub request_external_three_ds_authentication:
Option<common_enums::External3dsAuthenticationRequest>,
#[schema(value_type = Option<UpdateActiveAttempt>)]
/// Whether to set / unset the active attempt id
pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>,
/// Allow partial authorization for this payment
#[schema(value_type = Option<bool>, default = false)]
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[cfg(feature = "v2")]
impl PaymentsUpdateIntentRequest {
pub fn update_feature_metadata_and_active_attempt_with_api(
feature_metadata: FeatureMetadata,
set_active_attempt_id: api_enums::UpdateActiveAttempt,
) -> Self {
Self {
feature_metadata: Some(feature_metadata),
set_active_attempt_id: Some(set_active_attempt_id),
amount_details: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing: None,
shipping: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
enable_partial_authorization: None,
}
}
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[cfg(feature = "v2")]
pub struct PaymentsIntentResponse {
/// Global Payment Id for the payment
#[schema(value_type = String)]
pub id: id_type::GlobalPaymentId,
/// The status of the payment
#[schema(value_type = IntentStatus, example = "succeeded")]
pub status: common_enums::IntentStatus,
/// The amount details for the payment
pub amount_details: AmountDetailsResponse,
/// It's a token used for client side verification.
#[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")]
pub client_secret: Option<Secret<String>>,
/// The identifier for the profile. This is inferred from the `x-profile-id` header
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant.
#[schema(
value_type = Option<String>,
min_length = 30,
max_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4"
)]
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The routing algorithm id to be used for the payment
#[schema(value_type = Option<String>)]
pub routing_algorithm_id: Option<id_type::RoutingId>,
#[schema(value_type = CaptureMethod, example = "automatic")]
pub capture_method: api_enums::CaptureMethod,
/// The authentication type for the payment
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")]
pub authentication_type: Option<api_enums::AuthenticationType>,
/// The billing details of the payment. This address will be used for invoicing.
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// The shipping address for the payment
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// The identifier for the customer
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub customer_id: Option<id_type::GlobalCustomerId>,
/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
#[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)]
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
/// A description for the payment
#[schema(example = "It's my first payment request", value_type = Option<String>)]
pub description: Option<common_utils::types::Description>,
/// The URL to which you want the user to be redirected after the completion of the payment operation
#[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
pub return_url: Option<common_utils::types::Url>,
#[schema(value_type = FutureUsage, example = "off_session")]
pub setup_future_usage: api_enums::FutureUsage,
/// Apply MIT exemption for a payment
#[schema(value_type = MitExemptionRequest)]
pub apply_mit_exemption: common_enums::MitExemptionRequest,
/// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
#[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)]
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
/// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
#[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount" : 69000
"product_img_link" : "https://dummy-img-link.com"
}]"#)]
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
/// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
#[schema(value_type = Option<Vec<PaymentMethodType>>)]
pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
#[schema(value_type = Option<ConnectorMetadata>)]
pub connector_metadata: Option<ConnectorMetadata>,
/// Additional data that might be required by hyperswitch based on the requested features by the merchants.
#[schema(value_type = Option<FeatureMetadata>)]
pub feature_metadata: Option<FeatureMetadata>,
/// Whether to generate the payment link for this payment or not (if applicable)
#[schema(value_type = EnablePaymentLinkRequest)]
pub payment_link_enabled: common_enums::EnablePaymentLinkRequest,
/// Configure a custom payment link for the particular payment
#[schema(value_type = Option<PaymentLinkConfigRequest>)]
pub payment_link_config: Option<admin::PaymentLinkConfigRequest>,
///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.
#[schema(value_type = RequestIncrementalAuthorization)]
pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = SplitTxnsEnabled, default = "skip")]
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
///Will be used to expire client secret after certain amount of time to be supplied in seconds
#[serde(with = "common_utils::custom_serde::iso8601")]
pub expires_on: PrimitiveDateTime,
/// Additional data related to some frm(Fraud Risk Management) connectors
#[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// Whether to perform external authentication (if applicable)
#[schema(value_type = External3dsAuthenticationRequest)]
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
/// The type of the payment that differentiates between normal and various types of mandate payments
#[schema(value_type = PaymentType)]
pub payment_type: api_enums::PaymentType,
/// Allow partial authorization for this payment
#[schema(value_type = Option<bool>, default = false)]
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[cfg(feature = "v2")]
pub struct RevenueRecoveryGetIntentResponse {
/// Global Payment Id for the payment
#[schema(value_type = String)]
pub id: id_type::GlobalPaymentId,
/// The recovery status of the payment
#[schema(value_type = RecoveryStatus, example = "scheduled")]
pub status: common_enums::RecoveryStatus,
/// The amount details for the payment
pub amount_details: AmountDetailsResponse,
/// It's a token used for client side verification.
#[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")]
pub client_secret: Option<Secret<String>>,
/// The identifier for the profile. This is inferred from the `x-profile-id` header
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant.
#[schema(
value_type = Option<String>,
min_length = 30,
max_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4"
)]
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The routing algorithm id to be used for the payment
#[schema(value_type = Option<String>)]
pub routing_algorithm_id: Option<id_type::RoutingId>,
#[schema(value_type = CaptureMethod, example = "automatic")]
pub capture_method: api_enums::CaptureMethod,
/// The authentication type for the payment
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")]
pub authentication_type: Option<api_enums::AuthenticationType>,
/// The billing details of the payment. This address will be used for invoicing.
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// The shipping address for the payment
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// The identifier for the customer
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub customer_id: Option<id_type::GlobalCustomerId>,
/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/connector_enums.rs | crates/api_models/src/connector_enums.rs | pub use common_enums::connector_enums::Connector;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/external_service_auth.rs | crates/api_models/src/external_service_auth.rs | use common_utils::{id_type, pii};
use masking::Secret;
#[derive(Debug, serde::Serialize)]
pub struct ExternalTokenResponse {
pub token: Secret<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ExternalVerifyTokenRequest {
pub token: Secret<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ExternalSignoutTokenRequest {
pub token: Secret<String>,
}
#[derive(serde::Serialize, Debug)]
#[serde(untagged)]
pub enum ExternalVerifyTokenResponse {
Hypersense {
user_id: String,
merchant_id: id_type::MerchantId,
name: Secret<String>,
email: pii::Email,
},
}
impl ExternalVerifyTokenResponse {
pub fn get_user_id(&self) -> &str {
match self {
Self::Hypersense { user_id, .. } => user_id,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/tokenization.rs | crates/api_models/src/tokenization.rs | use common_utils::id_type;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::{schema, ToSchema};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct GenericTokenizationResponse {
/// Unique identifier returned by the tokenization service
#[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
pub id: id_type::GlobalTokenId,
/// Created time of the tokenization id
#[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")]
pub created_at: PrimitiveDateTime,
/// Status of the tokenization id created
#[schema(value_type = String,example = "enabled")]
pub flag: common_enums::TokenizationFlag,
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct GenericTokenizationRequest {
/// Customer ID for which the tokenization is requested
#[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
pub customer_id: id_type::GlobalCustomerId,
/// Request for tokenization which contains the data to be tokenized
#[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))]
pub token_request: masking::Secret<serde_json::Value>,
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct DeleteTokenDataRequest {
/// Customer ID for which the tokenization is requested
#[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
pub customer_id: id_type::GlobalCustomerId,
/// Session ID associated with the tokenization request
#[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")]
pub session_id: id_type::GlobalPaymentMethodSessionId,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct DeleteTokenDataResponse {
/// Unique identifier returned by the tokenization service
#[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
pub id: id_type::GlobalTokenId,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics.rs | crates/api_models/src/analytics.rs | use std::collections::HashSet;
pub use common_utils::types::TimeRange;
use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo};
use masking::Secret;
use self::{
active_payments::ActivePaymentsMetrics,
api_event::{ApiEventDimensions, ApiEventMetrics},
auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics},
disputes::{DisputeDimensions, DisputeMetrics},
frm::{FrmDimensions, FrmMetrics},
payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics},
payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
refunds::{RefundDimensions, RefundDistributions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
};
pub mod active_payments;
pub mod api_event;
pub mod auth_events;
pub mod connector_events;
pub mod disputes;
pub mod frm;
pub mod outgoing_webhook_event;
pub mod payment_intents;
pub mod payments;
pub mod refunds;
pub mod routing_events;
pub mod sdk_events;
pub mod search;
#[derive(Debug, serde::Serialize)]
pub struct NameDescription {
pub name: String,
pub desc: String,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetInfoResponse {
pub metrics: Vec<NameDescription>,
pub download_dimensions: Option<Vec<NameDescription>>,
pub dimensions: Vec<NameDescription>,
}
#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub struct TimeSeries {
pub granularity: Granularity,
}
#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub enum Granularity {
#[serde(rename = "G_ONEMIN")]
OneMin,
#[serde(rename = "G_FIVEMIN")]
FiveMin,
#[serde(rename = "G_FIFTEENMIN")]
FifteenMin,
#[serde(rename = "G_THIRTYMIN")]
ThirtyMin,
#[serde(rename = "G_ONEHOUR")]
OneHour,
#[serde(rename = "G_ONEDAY")]
OneDay,
}
pub trait ForexMetric {
fn is_forex_metric(&self) -> bool;
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AnalyticsRequest {
pub payment_intent: Option<GetPaymentIntentMetricRequest>,
pub payment_attempt: Option<GetPaymentMetricRequest>,
pub refund: Option<GetRefundMetricRequest>,
pub dispute: Option<GetDisputeMetricRequest>,
}
impl AnalyticsRequest {
pub fn requires_forex_functionality(&self) -> bool {
self.payment_attempt
.as_ref()
.map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
.unwrap_or_default()
|| self
.payment_intent
.as_ref()
.map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
.unwrap_or_default()
|| self
.refund
.as_ref()
.map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
.unwrap_or_default()
|| self
.dispute
.as_ref()
.map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
.unwrap_or_default()
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<PaymentDimensions>,
#[serde(default)]
pub filters: payments::PaymentFilters,
pub metrics: HashSet<PaymentMetrics>,
pub distribution: Option<PaymentDistributionBody>,
#[serde(default)]
pub delta: bool,
}
#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub enum QueryLimit {
#[serde(rename = "TOP_5")]
Top5,
#[serde(rename = "TOP_10")]
Top10,
}
#[allow(clippy::from_over_into)]
impl Into<u64> for QueryLimit {
fn into(self) -> u64 {
match self {
Self::Top5 => 5,
Self::Top10 => 10,
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentDistributionBody {
pub distribution_for: PaymentDistributions,
pub distribution_cardinality: QueryLimit,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundDistributionBody {
pub distribution_for: RefundDistributions,
pub distribution_cardinality: QueryLimit,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportRequest {
pub time_range: TimeRange,
pub emails: Option<Vec<Secret<String, EmailStrategy>>>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateReportRequest {
pub request: ReportRequest,
pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub auth: AuthInfo,
pub email: Secret<String, EmailStrategy>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentIntentMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<PaymentIntentDimensions>,
#[serde(default)]
pub filters: payment_intents::PaymentIntentFilters,
pub metrics: HashSet<PaymentIntentMetrics>,
#[serde(default)]
pub delta: bool,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRefundMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<RefundDimensions>,
#[serde(default)]
pub filters: refunds::RefundFilters,
pub metrics: HashSet<RefundMetrics>,
pub distribution: Option<RefundDistributionBody>,
#[serde(default)]
pub delta: bool,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFrmMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<FrmDimensions>,
#[serde(default)]
pub filters: frm::FrmFilters,
pub metrics: HashSet<FrmMetrics>,
#[serde(default)]
pub delta: bool,
}
impl ApiEventMetric for GetFrmMetricRequest {}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSdkEventMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<SdkEventDimensions>,
#[serde(default)]
pub filters: sdk_events::SdkEventFilters,
pub metrics: HashSet<SdkEventMetrics>,
#[serde(default)]
pub delta: bool,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAuthEventMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<AuthEventDimensions>,
#[serde(default)]
pub filters: AuthEventFilters,
#[serde(default)]
pub metrics: HashSet<AuthEventMetrics>,
#[serde(default)]
pub delta: bool,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetActivePaymentsMetricRequest {
#[serde(default)]
pub metrics: HashSet<ActivePaymentsMetrics>,
pub time_range: TimeRange,
}
#[derive(Debug, serde::Serialize)]
pub struct AnalyticsMetadata {
pub current_time_range: TimeRange,
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentsAnalyticsMetadata {
pub total_payment_processed_amount: Option<u64>,
pub total_payment_processed_amount_in_usd: Option<u64>,
pub total_payment_processed_amount_without_smart_retries: Option<u64>,
pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub total_payment_processed_count: Option<u64>,
pub total_payment_processed_count_without_smart_retries: Option<u64>,
pub total_failure_reasons_count: Option<u64>,
pub total_failure_reasons_count_without_smart_retries: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentIntentsAnalyticsMetadata {
pub total_success_rate: Option<f64>,
pub total_success_rate_without_smart_retries: Option<f64>,
pub total_smart_retried_amount: Option<u64>,
pub total_smart_retried_amount_without_smart_retries: Option<u64>,
pub total_payment_processed_amount: Option<u64>,
pub total_payment_processed_amount_without_smart_retries: Option<u64>,
pub total_smart_retried_amount_in_usd: Option<u64>,
pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>,
pub total_payment_processed_amount_in_usd: Option<u64>,
pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>,
pub total_payment_processed_count: Option<u64>,
pub total_payment_processed_count_without_smart_retries: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct RefundsAnalyticsMetadata {
pub total_refund_success_rate: Option<f64>,
pub total_refund_processed_amount: Option<u64>,
pub total_refund_processed_amount_in_usd: Option<u64>,
pub total_refund_processed_count: Option<u64>,
pub total_refund_reason_count: Option<u64>,
pub total_refund_error_message_count: Option<u64>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentFiltersRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<PaymentDimensions>,
}
#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentFiltersResponse {
pub query_data: Vec<FilterValue>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FilterValue {
pub dimension: PaymentDimensions,
pub values: Vec<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentIntentFiltersRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<PaymentIntentDimensions>,
}
#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentIntentFiltersResponse {
pub query_data: Vec<PaymentIntentFilterValue>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentIntentFilterValue {
pub dimension: PaymentIntentDimensions,
pub values: Vec<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRefundFilterRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<RefundDimensions>,
}
#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RefundFiltersResponse {
pub query_data: Vec<RefundFilterValue>,
}
#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RefundFilterValue {
pub dimension: RefundDimensions,
pub values: Vec<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFrmFilterRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<FrmDimensions>,
}
impl ApiEventMetric for GetFrmFilterRequest {}
#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FrmFiltersResponse {
pub query_data: Vec<FrmFilterValue>,
}
impl ApiEventMetric for FrmFiltersResponse {}
#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FrmFilterValue {
pub dimension: FrmDimensions,
pub values: Vec<String>,
}
impl ApiEventMetric for FrmFilterValue {}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSdkEventFiltersRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<SdkEventDimensions>,
}
#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkEventFiltersResponse {
pub query_data: Vec<SdkEventFilterValue>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkEventFilterValue {
pub dimension: SdkEventDimensions,
pub values: Vec<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct DisputesAnalyticsMetadata {
pub total_disputed_amount: Option<u64>,
pub total_dispute_lost_amount: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [AnalyticsMetadata; 1],
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [PaymentsAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentIntentsMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [PaymentIntentsAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundsMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [RefundsAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DisputesMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [DisputesAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventFiltersRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<ApiEventDimensions>,
}
#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiEventFiltersResponse {
pub query_data: Vec<ApiEventFilterValue>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiEventFilterValue {
pub dimension: ApiEventDimensions,
pub values: Vec<String>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<ApiEventDimensions>,
#[serde(default)]
pub filters: api_event::ApiEventFilters,
pub metrics: HashSet<ApiEventMetrics>,
#[serde(default)]
pub delta: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDisputeFilterRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<DisputeDimensions>,
}
#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DisputeFiltersResponse {
pub query_data: Vec<DisputeFilterValue>,
}
#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DisputeFilterValue {
pub dimension: DisputeDimensions,
pub values: Vec<String>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDisputeMetricRequest {
pub time_series: Option<TimeSeries>,
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<DisputeDimensions>,
#[serde(default)]
pub filters: disputes::DisputeFilters,
pub metrics: HashSet<DisputeMetrics>,
#[serde(default)]
pub delta: bool,
}
#[derive(Clone, Debug, Default, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SankeyResponse {
pub count: i64,
pub status: String,
pub refunds_status: Option<String>,
pub dispute_status: Option<String>,
pub first_attempt: i64,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAuthEventFilterRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<AuthEventDimensions>,
}
#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthEventFiltersResponse {
pub query_data: Vec<AuthEventFilterValue>,
}
#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthEventFilterValue {
pub dimension: AuthEventDimensions,
pub values: Vec<String>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthEventMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [AuthEventsAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Serialize)]
pub struct AuthEventsAnalyticsMetadata {
pub total_error_message_count: Option<u64>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/payments/trait_impls.rs | crates/api_models/src/payments/trait_impls.rs | #[cfg(feature = "v1")]
use common_enums::enums;
#[cfg(feature = "v1")]
use common_utils::errors;
#[cfg(feature = "v1")]
use crate::payments;
#[cfg(feature = "v1")]
impl crate::ValidateFieldAndGet<payments::PaymentsRequest>
for common_types::primitive_wrappers::RequestExtendedAuthorizationBool
{
fn validate_field_and_get(
&self,
request: &payments::PaymentsRequest,
) -> errors::CustomResult<Self, errors::ValidationError>
where
Self: Sized,
{
match request.capture_method{
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::Scheduled)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Err(error_stack::report!(errors::ValidationError::InvalidValue { message: "request_extended_authorization must be sent only if capture method is manual or manual_multiple".to_string() })),
Some(enums::CaptureMethod::Manual)
| Some(enums::CaptureMethod::ManualMultiple) => Ok(*self)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/payments/additional_info.rs | crates/api_models/src/payments/additional_info.rs | use common_utils::new_type::{
MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId,
};
use masking::Secret;
use smithy::SmithyModel;
use utoipa::ToSchema;
use crate::enums as api_enums;
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum BankDebitAdditionalData {
#[smithy(value_type = "AchBankDebitAdditionalData")]
Ach(Box<AchBankDebitAdditionalData>),
#[smithy(value_type = "BacsBankDebitAdditionalData")]
Bacs(Box<BacsBankDebitAdditionalData>),
#[smithy(value_type = "BecsBankDebitAdditionalData")]
Becs(Box<BecsBankDebitAdditionalData>),
#[smithy(value_type = "SepaBankDebitAdditionalData")]
Sepa(Box<SepaBankDebitAdditionalData>),
SepaGuarenteedDebit(Box<SepaBankDebitAdditionalData>),
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct AchBankDebitAdditionalData {
/// Partially masked account number for ach bank debit payment
#[schema(value_type = String, example = "0001****3456")]
#[smithy(value_type = "String")]
pub account_number: MaskedBankAccount,
/// Partially masked routing number for ach bank debit payment
#[schema(value_type = String, example = "110***000")]
#[smithy(value_type = "String")]
pub routing_number: MaskedRoutingNumber,
/// Card holder's name
#[schema(value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub card_holder_name: Option<Secret<String>>,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub bank_account_holder_name: Option<Secret<String>>,
/// Name of the bank
#[schema(value_type = Option<BankNames>, example = "ach")]
#[smithy(value_type = "Option<BankNames>")]
pub bank_name: Option<common_enums::BankNames>,
/// Bank account type
#[schema(value_type = Option<BankType>, example = "checking")]
#[smithy(value_type = "Option<BankType>")]
pub bank_type: Option<common_enums::BankType>,
/// Bank holder entity type
#[schema(value_type = Option<BankHolderType>, example = "personal")]
#[smithy(value_type = "Option<BankHolderType>")]
pub bank_holder_type: Option<common_enums::BankHolderType>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct BacsBankDebitAdditionalData {
/// Partially masked account number for Bacs payment method
#[schema(value_type = String, example = "0001****3456")]
#[smithy(value_type = "String")]
pub account_number: MaskedBankAccount,
/// Partially masked sort code for Bacs payment method
#[schema(value_type = String, example = "108800")]
#[smithy(value_type = "String")]
pub sort_code: MaskedSortCode,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub bank_account_holder_name: Option<Secret<String>>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct BecsBankDebitAdditionalData {
/// Partially masked account number for Becs payment method
#[schema(value_type = String, example = "0001****3456")]
#[smithy(value_type = "String")]
pub account_number: MaskedBankAccount,
/// Bank-State-Branch (bsb) number
#[schema(value_type = String, example = "000000")]
#[smithy(value_type = "String")]
pub bsb_number: Secret<String>,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub bank_account_holder_name: Option<Secret<String>>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct SepaBankDebitAdditionalData {
/// Partially masked international bank account number (iban) for SEPA
#[schema(value_type = String, example = "DE8937******013000")]
#[smithy(value_type = "String")]
pub iban: MaskedIban,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
#[smithy(value_type = "Option<String>")]
pub bank_account_holder_name: Option<Secret<String>>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum BankRedirectDetails {
#[smithy(value_type = "BancontactBankRedirectAdditionalData")]
BancontactCard(Box<BancontactBankRedirectAdditionalData>),
#[smithy(value_type = "BlikBankRedirectAdditionalData")]
Blik(Box<BlikBankRedirectAdditionalData>),
#[smithy(value_type = "GiropayBankRedirectAdditionalData")]
Giropay(Box<GiropayBankRedirectAdditionalData>),
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct BancontactBankRedirectAdditionalData {
/// Last 4 digits of the card number
#[schema(value_type = Option<String>, example = "4242")]
#[smithy(value_type = "Option<String>")]
pub last4: Option<String>,
/// The card's expiry month
#[schema(value_type = Option<String>, example = "12")]
#[smithy(value_type = "Option<String>")]
pub card_exp_month: Option<Secret<String>>,
/// The card's expiry year
#[schema(value_type = Option<String>, example = "24")]
#[smithy(value_type = "Option<String>")]
pub card_exp_year: Option<Secret<String>>,
/// The card holder's name
#[schema(value_type = Option<String>, example = "John Test")]
#[smithy(value_type = "Option<String>")]
pub card_holder_name: Option<Secret<String>>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct BlikBankRedirectAdditionalData {
#[schema(value_type = Option<String>, example = "3GD9MO")]
#[smithy(value_type = "Option<String>")]
pub blik_code: Option<String>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct GiropayBankRedirectAdditionalData {
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
/// Masked bank account bic code
pub bic: Option<MaskedSortCode>,
/// Partially masked international bank account number (iban) for SEPA
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub iban: Option<MaskedIban>,
/// Country for bank payment
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
#[smithy(value_type = "Option<CountryAlpha2>")]
pub country: Option<api_enums::CountryAlpha2>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum BankTransferAdditionalData {
#[smithy(nested_value_type)]
Ach {},
#[smithy(nested_value_type)]
Sepa {},
#[smithy(nested_value_type)]
Bacs {},
#[smithy(nested_value_type)]
Multibanco {},
#[smithy(nested_value_type)]
Permata {},
#[smithy(nested_value_type)]
Bca {},
#[smithy(nested_value_type)]
BniVa {},
#[smithy(nested_value_type)]
BriVa {},
#[smithy(nested_value_type)]
CimbVa {},
#[smithy(nested_value_type)]
DanamonVa {},
#[smithy(nested_value_type)]
MandiriVa {},
#[smithy(value_type = "PixBankTransferAdditionalData")]
Pix(Box<PixBankTransferAdditionalData>),
#[smithy(nested_value_type)]
Pse {},
#[smithy(value_type = "LocalBankTransferAdditionalData")]
LocalBankTransfer(Box<LocalBankTransferAdditionalData>),
#[smithy(nested_value_type)]
InstantBankTransfer {},
#[smithy(nested_value_type)]
InstantBankTransferFinland {},
#[smithy(nested_value_type)]
InstantBankTransferPoland {},
#[smithy(nested_value_type)]
IndonesianBankTransfer {
#[schema(value_type = Option<BankNames>, example = "bri")]
#[smithy(value_type = "Option<BankNames>")]
bank_name: Option<common_enums::BankNames>,
},
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct PixBankTransferAdditionalData {
/// Partially masked unique key for pix transfer
#[schema(value_type = Option<String>, example = "a1f4102e ****** 6fa48899c1d1")]
#[smithy(value_type = "Option<String>")]
pub pix_key: Option<MaskedBankAccount>,
/// Partially masked CPF - CPF is a Brazilian tax identification number
#[schema(value_type = Option<String>, example = "**** 124689")]
#[smithy(value_type = "Option<String>")]
pub cpf: Option<MaskedBankAccount>,
/// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number
#[schema(value_type = Option<String>, example = "**** 417312")]
#[smithy(value_type = "Option<String>")]
pub cnpj: Option<MaskedBankAccount>,
/// Partially masked source bank account number
#[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")]
#[smithy(value_type = "Option<String>")]
pub source_bank_account_id: Option<MaskedBankAccount>,
/// Partially masked destination bank account number _Deprecated: Will be removed in next stable release._
#[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b", deprecated)]
#[smithy(value_type = "Option<String>")]
pub destination_bank_account_id: Option<MaskedBankAccount>,
/// The expiration date and time for the Pix QR code in ISO 8601 format
#[schema(value_type = Option<String>, example = "2025-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<String>")]
pub expiry_date: Option<time::PrimitiveDateTime>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct LocalBankTransferAdditionalData {
/// Partially masked bank code
#[schema(value_type = Option<String>, example = "**** OA2312")]
#[smithy(value_type = "Option<String>")]
pub bank_code: Option<MaskedBankAccount>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum GiftCardAdditionalData {
#[smithy(value_type = "String")]
Givex(Box<GivexGiftCardAdditionalData>),
#[smithy(nested_value_type)]
PaySafeCard {},
#[smithy(nested_value_type)]
BhnCardNetwork {},
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct GivexGiftCardAdditionalData {
/// Last 4 digits of the gift card number
#[schema(value_type = String, example = "4242")]
#[smithy(value_type = "String")]
pub last4: Secret<String>,
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CardTokenAdditionalData {
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
#[smithy(value_type = "String")]
pub card_holder_name: Option<Secret<String>>,
}
#[derive(
Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum UpiAdditionalData {
#[smithy(value_type = "UpiCollectAdditionalData")]
UpiCollect(Box<UpiCollectAdditionalData>),
#[schema(value_type = UpiIntentData)]
#[smithy(value_type = "UpiIntentData")]
UpiIntent(Box<super::UpiIntentData>),
#[schema(value_type = UpiQrData)]
UpiQr(Box<super::UpiQrData>),
}
#[derive(
Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct UpiCollectAdditionalData {
/// Masked VPA ID
#[schema(value_type = Option<String>, example = "ab********@okhdfcbank")]
#[smithy(value_type = "Option<String>")]
pub vpa_id: Option<MaskedUpiVpaId>,
}
#[derive(
Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct WalletAdditionalDataForCard {
/// Last 4 digits of the card number
#[smithy(value_type = "String")]
pub last4: String,
/// The information of the payment method
#[smithy(value_type = "String")]
pub card_network: String,
/// The type of payment method
#[serde(rename = "type")]
#[smithy(value_type = "Option<String>")]
pub card_type: Option<String>,
/// The card's expiry month
#[schema(value_type = Option<String>, example = "03")]
pub card_exp_month: Option<Secret<String>>,
/// The card's expiry year
#[schema(value_type = Option<String>, example = "25")]
pub card_exp_year: Option<Secret<String>>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/user_role/role.rs | crates/api_models/src/user_role/role.rs | use common_enums::{
EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope,
};
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleRequest {
pub role_name: String,
pub groups: Vec<PermissionGroup>,
pub role_scope: RoleScope,
pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleV2Request {
pub role_name: String,
pub role_scope: RoleScope,
pub entity_type: Option<EntityType>,
pub parent_groups: Vec<ParentGroupInfoRequest>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateRoleRequest {
pub groups: Option<Vec<PermissionGroup>>,
pub role_name: Option<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithGroupsResponse {
pub role_id: String,
pub groups: Vec<PermissionGroup>,
pub role_name: String,
pub role_scope: RoleScope,
pub entity_type: EntityType,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithParents {
pub role_id: String,
pub parent_groups: Vec<ParentGroupDescription>,
pub role_name: String,
pub role_scope: RoleScope,
}
#[derive(Debug, serde::Serialize)]
pub struct ParentGroupDescription {
pub name: ParentGroup,
pub description: String,
pub scopes: Vec<PermissionScope>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ParentGroupInfoRequest {
pub name: ParentGroup,
pub scopes: Vec<PermissionScope>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListRolesQueryParams {
pub entity_type: Option<EntityType>,
pub groups: Option<bool>,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponseNew {
pub role_id: String,
pub role_name: String,
pub entity_type: EntityType,
pub groups: Vec<PermissionGroup>,
pub scope: RoleScope,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponseWithParentsGroup {
pub role_id: String,
pub role_name: String,
pub entity_type: EntityType,
pub parent_groups: Vec<ParentGroupDescription>,
pub role_scope: RoleScope,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetRoleRequest {
pub role_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListRolesAtEntityLevelRequest {
pub entity_type: EntityType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetParentGroupsInfoQueryParams {
pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum RoleCheckType {
Invite,
Update,
}
#[derive(Debug, serde::Serialize, Clone)]
pub struct MinimalRoleInfo {
pub role_id: String,
pub role_name: String,
}
#[derive(Debug, serde::Serialize)]
pub struct GroupsAndResources {
pub groups: Vec<PermissionGroup>,
pub resources: Vec<Resource>,
}
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum ListRolesResponse {
WithGroups(Vec<RoleInfoResponseNew>),
WithParentGroups(Vec<RoleInfoResponseWithParentsGroup>),
}
#[derive(Debug, serde::Serialize)]
pub struct ParentGroupInfo {
pub name: ParentGroup,
pub resources: Vec<Resource>,
pub scopes: Vec<PermissionScope>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/user/theme.rs | crates/api_models/src/user/theme.rs | use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
use common_enums::EntityType;
use common_utils::{
id_type,
types::user::{EmailThemeConfig, ThemeLineage},
};
use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
pub struct GetThemeResponse {
pub theme_id: String,
pub theme_name: String,
pub entity_type: EntityType,
pub tenant_id: id_type::TenantId,
pub org_id: Option<id_type::OrganizationId>,
pub merchant_id: Option<id_type::MerchantId>,
pub profile_id: Option<id_type::ProfileId>,
pub email_config: EmailThemeConfig,
pub theme_data: ThemeData,
}
#[derive(Debug, MultipartForm)]
pub struct UploadFileAssetData {
pub asset_name: Text<String>,
#[multipart(limit = "10MB")]
pub asset_data: Bytes,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UploadFileRequest {
pub asset_name: String,
pub asset_data: Secret<Vec<u8>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CreateThemeRequest {
pub lineage: ThemeLineage,
pub theme_name: String,
pub theme_data: ThemeData,
pub email_config: Option<EmailThemeConfig>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CreateUserThemeRequest {
pub entity_type: EntityType,
pub theme_name: String,
pub theme_data: ThemeData,
pub email_config: Option<EmailThemeConfig>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UpdateThemeRequest {
pub theme_data: Option<ThemeData>,
pub email_config: Option<EmailThemeConfig>,
}
// All the below structs are for the theme.json file,
// which will be used by frontend to style the dashboard.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ThemeData {
settings: Settings,
urls: Option<Urls>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Settings {
colors: Colors,
sidebar: Option<Sidebar>,
typography: Option<Typography>,
buttons: Buttons,
borders: Option<Borders>,
spacing: Option<Spacing>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Colors {
primary: String,
secondary: Option<String>,
background: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Sidebar {
primary: String,
text_color: Option<String>,
text_color_primary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Typography {
font_family: Option<String>,
font_size: Option<String>,
heading_font_size: Option<String>,
text_color: Option<String>,
link_color: Option<String>,
link_hover_color: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Buttons {
primary: PrimaryButton,
secondary: Option<SecondaryButton>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PrimaryButton {
background_color: Option<String>,
text_color: Option<String>,
hover_background_color: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct SecondaryButton {
background_color: Option<String>,
text_color: Option<String>,
hover_background_color: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Borders {
default_radius: Option<String>,
border_color: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Spacing {
padding: Option<String>,
margin: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Urls {
favicon_url: Option<String>,
logo_url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub struct EntityTypeQueryParam {
pub entity_type: EntityType,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/user/sample_data.rs | crates/api_models/src/user/sample_data.rs | use common_enums::{AuthenticationType, CountryAlpha2};
use time::PrimitiveDateTime;
use crate::enums::Connector;
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SampleDataRequest {
pub record: Option<usize>,
pub connector: Option<Vec<Connector>>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub start_time: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub end_time: Option<PrimitiveDateTime>,
// The amount for each sample will be between min_amount and max_amount (in dollars)
pub min_amount: Option<i64>,
pub max_amount: Option<i64>,
pub currency: Option<Vec<common_enums::Currency>>,
pub auth_type: Option<Vec<AuthenticationType>>,
pub business_country: Option<CountryAlpha2>,
pub business_label: Option<String>,
pub profile_id: Option<common_utils::id_type::ProfileId>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/user/dashboard_metadata.rs | crates/api_models/src/user/dashboard_metadata.rs | use common_enums::{CountryAlpha2, MerchantProductType};
use common_types::primitive_wrappers::SafeString;
use common_utils::{id_type, pii};
use masking::Secret;
use strum::EnumString;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum SetMetaDataRequest {
ProductionAgreement(ProductionAgreementRequest),
SetupProcessor(SetupProcessor),
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected(ProcessorConnected),
SecondProcessorConnected(ProcessorConnected),
ConfiguredRouting(ConfiguredRouting),
TestPayment(TestPayment),
IntegrationMethod(IntegrationMethod),
ConfigurationType(ConfigurationType),
IntegrationCompleted,
SPRoutingConfigured(ConfiguredRouting),
Feedback(Feedback),
ProdIntent(ProdIntent),
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
#[serde(skip)]
IsChangePasswordRequired,
OnboardingSurvey(OnboardingSurvey),
ReconStatus(ReconStatus),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProductionAgreementRequest {
pub version: String,
#[serde(skip_deserializing)]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SetupProcessor {
pub connector_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProcessorConnected {
pub processor_id: id_type::MerchantConnectorAccountId,
pub processor_name: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct OnboardingSurvey {
pub designation: Option<SafeString>,
pub about_business: Option<SafeString>,
pub business_website: Option<SafeString>,
pub hyperswitch_req: Option<SafeString>,
pub major_markets: Option<Vec<SafeString>>,
pub business_size: Option<SafeString>,
pub required_features: Option<Vec<SafeString>>,
pub required_processors: Option<Vec<SafeString>>,
pub planned_live_date: Option<SafeString>,
pub miscellaneous: Option<SafeString>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ConfiguredRouting {
pub routing_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TestPayment {
pub payment_id: id_type::PaymentId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct IntegrationMethod {
pub integration_type: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum ConfigurationType {
Single,
Multiple,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct Feedback {
pub email: pii::Email,
pub description: Option<SafeString>,
pub rating: Option<i32>,
pub category: Option<SafeString>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ProdIntent {
pub legal_business_name: Option<SafeString>,
pub business_label: Option<SafeString>,
pub business_location: Option<CountryAlpha2>,
pub display_name: Option<SafeString>,
pub poc_email: Option<pii::Email>,
pub business_type: Option<SafeString>,
pub business_identifier: Option<SafeString>,
pub business_website: Option<SafeString>,
pub poc_name: Option<Secret<SafeString>>,
pub poc_contact: Option<Secret<SafeString>>,
pub comments: Option<SafeString>,
pub is_completed: bool,
#[serde(default)]
pub product_type: MerchantProductType,
pub business_country_name: Option<SafeString>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ReconStatus {
pub is_order_data_set: bool,
pub is_processor_data_set: bool,
}
#[derive(Debug, serde::Deserialize, EnumString, serde::Serialize)]
pub enum GetMetaDataRequest {
ProductionAgreement,
SetupProcessor,
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected,
SecondProcessorConnected,
ConfiguredRouting,
TestPayment,
IntegrationMethod,
ConfigurationType,
IntegrationCompleted,
StripeConnected,
PaypalConnected,
SPRoutingConfigured,
Feedback,
ProdIntent,
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
OnboardingSurvey,
ReconStatus,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(transparent)]
pub struct GetMultipleMetaDataPayload {
pub results: Vec<GetMetaDataRequest>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetMultipleMetaDataRequest {
pub keys: String,
}
#[derive(Debug, serde::Serialize)]
pub enum GetMetaDataResponse {
ProductionAgreement(bool),
SetupProcessor(Option<SetupProcessor>),
ConfigureEndpoint(bool),
SetupComplete(bool),
FirstProcessorConnected(Option<ProcessorConnected>),
SecondProcessorConnected(Option<ProcessorConnected>),
ConfiguredRouting(Option<ConfiguredRouting>),
TestPayment(Option<TestPayment>),
IntegrationMethod(Option<IntegrationMethod>),
ConfigurationType(Option<ConfigurationType>),
IntegrationCompleted(bool),
StripeConnected(Option<ProcessorConnected>),
PaypalConnected(Option<ProcessorConnected>),
SPRoutingConfigured(Option<ConfiguredRouting>),
Feedback(Option<Feedback>),
ProdIntent(Option<ProdIntent>),
SPTestPayment(bool),
DownloadWoocom(bool),
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
OnboardingSurvey(Option<OnboardingSurvey>),
ReconStatus(Option<ReconStatus>),
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/errors/actix.rs | crates/api_models/src/errors/actix.rs | use super::types::ApiErrorResponse;
impl actix_web::ResponseError for ApiErrorResponse {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
Self::ForbiddenCommonResource(_) => StatusCode::FORBIDDEN,
Self::ForbiddenPrivateResource(_) => StatusCode::NOT_FOUND,
Self::Conflict(_) => StatusCode::CONFLICT,
Self::Gone(_) => StatusCode::GONE,
Self::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY,
Self::InternalServerError(_) => StatusCode::INTERNAL_SERVER_ERROR,
Self::NotImplemented(_) => StatusCode::NOT_IMPLEMENTED,
Self::ConnectorError(_, code) => *code,
Self::MethodNotAllowed(_) => StatusCode::METHOD_NOT_ALLOWED,
Self::NotFound(_) => StatusCode::NOT_FOUND,
Self::BadRequest(_) => StatusCode::BAD_REQUEST,
Self::DomainError(_) => StatusCode::OK,
}
}
fn error_response(&self) -> actix_web::HttpResponse {
use actix_web::http::header;
actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.body(self.to_string())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/errors/types.rs | crates/api_models/src/errors/types.rs | use reqwest::StatusCode;
use router_derive::PolymorphicSchema;
use serde::Serialize;
use utoipa::ToSchema;
#[derive(Debug, serde::Serialize)]
pub enum ErrorType {
InvalidRequestError,
RouterError,
ConnectorError,
}
#[derive(Debug, serde::Serialize, Clone)]
pub struct ApiError {
pub sub_code: &'static str,
pub error_identifier: u16,
pub error_message: String,
pub extra: Option<Extra>,
}
impl ApiError {
pub fn new(
sub_code: &'static str,
error_identifier: u16,
error_message: impl ToString,
extra: Option<Extra>,
) -> Self {
Self {
sub_code,
error_identifier,
error_message: error_message.to_string(),
extra,
}
}
}
#[derive(Debug, serde::Serialize, ToSchema, PolymorphicSchema)]
#[generate_schemas(GenericErrorResponseOpenApi)]
pub struct ErrorResponse {
#[serde(rename = "type")]
#[schema(
example = "invalid_request",
value_type = &'static str
)]
pub error_type: &'static str,
#[schema(
example = "Missing required param: {param}",
value_type = String
)]
pub message: String,
#[schema(
example = "IR_04",
value_type = String
)]
pub code: String,
#[serde(flatten)]
pub extra: Option<Extra>,
}
impl From<&ApiErrorResponse> for ErrorResponse {
fn from(value: &ApiErrorResponse) -> Self {
let error_info = value.get_internal_error();
let error_type = value.error_type();
Self {
code: format!("{}_{:02}", error_info.sub_code, error_info.error_identifier),
message: error_info.error_message.clone(),
error_type,
extra: error_info.extra.clone(),
}
}
}
#[derive(Debug, serde::Serialize, Default, Clone)]
pub struct Extra {
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_id: Option<common_utils::id_type::PaymentId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fields: Option<String>,
}
#[derive(Serialize, Debug, Clone)]
#[serde(tag = "type", content = "value")]
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
impl ::core::fmt::Display for ApiErrorResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let error_response: ErrorResponse = self.into();
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(&error_response)
.unwrap_or_else(|_| "API error response".to_string())
)
}
}
impl ApiErrorResponse {
pub(crate) fn get_internal_error(&self) -> &ApiError {
match self {
Self::Unauthorized(i)
| Self::ForbiddenCommonResource(i)
| Self::ForbiddenPrivateResource(i)
| Self::Conflict(i)
| Self::Gone(i)
| Self::Unprocessable(i)
| Self::InternalServerError(i)
| Self::NotImplemented(i)
| Self::NotFound(i)
| Self::MethodNotAllowed(i)
| Self::BadRequest(i)
| Self::DomainError(i)
| Self::ConnectorError(i, _) => i,
}
}
pub fn get_internal_error_mut(&mut self) -> &mut ApiError {
match self {
Self::Unauthorized(i)
| Self::ForbiddenCommonResource(i)
| Self::ForbiddenPrivateResource(i)
| Self::Conflict(i)
| Self::Gone(i)
| Self::Unprocessable(i)
| Self::InternalServerError(i)
| Self::NotImplemented(i)
| Self::NotFound(i)
| Self::MethodNotAllowed(i)
| Self::BadRequest(i)
| Self::DomainError(i)
| Self::ConnectorError(i, _) => i,
}
}
pub(crate) fn error_type(&self) -> &'static str {
match self {
Self::Unauthorized(_)
| Self::ForbiddenCommonResource(_)
| Self::ForbiddenPrivateResource(_)
| Self::Conflict(_)
| Self::Gone(_)
| Self::Unprocessable(_)
| Self::NotImplemented(_)
| Self::MethodNotAllowed(_)
| Self::NotFound(_)
| Self::BadRequest(_) => "invalid_request",
Self::InternalServerError(_) => "api",
Self::DomainError(_) => "blocked",
Self::ConnectorError(_, _) => "connector",
}
}
}
impl std::error::Error for ApiErrorResponse {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/process_tracker/revenue_recovery.rs | crates/api_models/src/process_tracker/revenue_recovery.rs | use common_utils::id_type;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::enums;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RevenueRecoveryResponse {
pub id: String,
pub name: Option<String>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub schedule_time_for_payment: Option<PrimitiveDateTime>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub schedule_time_for_psync: Option<PrimitiveDateTime>,
#[schema(value_type = ProcessTrackerStatus, example = "finish")]
pub status: enums::ProcessTrackerStatus,
pub business_status: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RevenueRecoveryId {
pub revenue_recovery_id: id_type::GlobalPaymentId,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RevenueRecoveryRetriggerRequest {
/// The task we want to resume
pub revenue_recovery_task: String,
/// Time at which the job was scheduled at
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub schedule_time: Option<PrimitiveDateTime>,
/// Status of The Process Tracker Task
pub status: enums::ProcessTrackerStatus,
/// Business Status of The Process Tracker Task
pub business_status: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/user.rs | crates/api_models/src/events/user.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
#[cfg(feature = "dummy_connector")]
use crate::user::sample_data::SampleDataRequest;
#[cfg(feature = "control_center_theme")]
use crate::user::theme::{
CreateThemeRequest, CreateUserThemeRequest, GetThemeResponse, UpdateThemeRequest,
UploadFileRequest,
};
use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
AcceptInviteFromEmailRequest, AcceptInviteResponse, AuthSelectRequest, AuthorizeResponse,
BeginTotpResponse, ChangePasswordRequest, CloneConnectorRequest, ConnectAccountRequest,
CreateInternalUserRequest, CreateTenantUserRequest, CreateUserAuthenticationMethodRequest,
CreateUserAuthenticationMethodResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest,
GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
GetUserRoleDetailsResponseV2, InviteUserRequest, PlatformAccountCreateRequest,
PlatformAccountCreateResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest,
RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest,
SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest,
UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse,
UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest,
VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
common_utils::impl_api_event_type!(
Miscellaneous,
(
SignUpRequest,
SignUpWithMerchantIdRequest,
ChangePasswordRequest,
GetMultipleMetaDataPayload,
GetMetaDataResponse,
GetMetaDataRequest,
SetMetaDataRequest,
SwitchOrganizationRequest,
SwitchMerchantRequest,
SwitchProfileRequest,
CreateInternalUserRequest,
CreateTenantUserRequest,
PlatformAccountCreateRequest,
PlatformAccountCreateResponse,
UserOrgMerchantCreateRequest,
UserMerchantAccountResponse,
UserMerchantCreate,
AuthorizeResponse,
ConnectAccountRequest,
ForgotPasswordRequest,
ResetPasswordRequest,
RotatePasswordRequest,
InviteUserRequest,
ReInviteUserRequest,
VerifyEmailRequest,
SendVerifyEmailRequest,
AcceptInviteFromEmailRequest,
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponseV2,
TokenResponse,
AcceptInviteResponse,
TwoFactorAuthStatusResponse,
TwoFactorStatus,
UserFromEmailRequest,
BeginTotpResponse,
VerifyRecoveryCodeRequest,
VerifyTotpRequest,
RecoveryCodes,
GetUserAuthenticationMethodsRequest,
CreateUserAuthenticationMethodRequest,
CreateUserAuthenticationMethodResponse,
UpdateUserAuthenticationMethodRequest,
GetSsoAuthUrlRequest,
SsoSignInRequest,
AuthSelectRequest,
CloneConnectorRequest
)
);
#[cfg(feature = "control_center_theme")]
common_utils::impl_api_event_type!(
Miscellaneous,
(
GetThemeResponse,
UploadFileRequest,
CreateThemeRequest,
CreateUserThemeRequest,
UpdateThemeRequest
)
);
#[cfg(feature = "dummy_connector")]
common_utils::impl_api_event_type!(Miscellaneous, (SampleDataRequest));
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/connector_onboarding.rs | crates/api_models/src/events/connector_onboarding.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::connector_onboarding::{
ActionUrlRequest, ActionUrlResponse, OnboardingStatus, OnboardingSyncRequest,
ResetTrackingIdRequest,
};
common_utils::impl_api_event_type!(
Miscellaneous,
(
ActionUrlRequest,
ActionUrlResponse,
OnboardingSyncRequest,
OnboardingStatus,
ResetTrackingIdRequest
)
);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/routing.rs | crates/api_models/src/events/routing.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::routing::{
ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper,
CreateDynamicRoutingWrapper, DynamicRoutingUpdateConfigQuery, EliminationRoutingPayloadWrapper,
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit,
RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery,
RuleMigrationResponse, RuleMigrationResult, SuccessBasedRoutingConfig,
SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingPath, ToggleDynamicRoutingQuery,
ToggleDynamicRoutingWrapper,
};
impl ApiEventMetric for RoutingKind {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for MerchantRoutingAlgorithm {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingAlgorithmId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingDictionaryRecord {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for LinkedRoutingConfigRetrieveResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingPayloadWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for ProfileDefaultRoutingConfig {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingRetrieveQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingConfigRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingRetrieveLinkQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingLinkWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for ToggleDynamicRoutingQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for SuccessBasedRoutingConfig {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for EliminationRoutingPayloadWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for ContractBasedRoutingPayloadWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for ContractBasedRoutingSetupPayloadWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for ToggleDynamicRoutingWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for CreateDynamicRoutingWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for DynamicRoutingUpdateConfigQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingVolumeSplitWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for ToggleDynamicRoutingPath {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingVolumeSplitResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RoutingVolumeSplit {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationResult {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for RuleMigrationError {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::DecideGatewayResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::OpenRouterDecideGatewayRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::UpdateScorePayload {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
impl ApiEventMetric for crate::open_router::UpdateScoreResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/revenue_recovery.rs | crates/api_models/src/events/revenue_recovery.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::process_tracker::revenue_recovery::{
RevenueRecoveryId, RevenueRecoveryResponse, RevenueRecoveryRetriggerRequest,
};
impl ApiEventMetric for RevenueRecoveryResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ProcessTracker)
}
}
impl ApiEventMetric for RevenueRecoveryId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ProcessTracker)
}
}
impl ApiEventMetric for RevenueRecoveryRetriggerRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ProcessTracker)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/dispute.rs | crates/api_models/src/events/dispute.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use super::{
DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve,
DisputeRetrieveRequest, DisputesAggregateResponse, SubmitEvidenceRequest,
};
impl ApiEventMetric for SubmitEvidenceRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for DisputeRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for DisputeResponsePaymentsRetrieve {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for DisputeResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for DeleteEvidenceRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for DisputesAggregateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/apple_pay_certificates_migration.rs | crates/api_models/src/events/apple_pay_certificates_migration.rs | use common_utils::events::ApiEventMetric;
use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse;
impl ApiEventMetric for ApplePayCertificatesMigrationResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/user_role.rs | crates/api_models/src/events/user_role.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
CreateRoleRequest, CreateRoleV2Request, GetParentGroupsInfoQueryParams, GetRoleRequest,
GroupsAndResources, ListRolesAtEntityLevelRequest, ListRolesQueryParams, ListRolesResponse,
ParentGroupInfoRequest, RoleInfoResponseNew, RoleInfoResponseWithParentsGroup,
RoleInfoWithGroupsResponse, RoleInfoWithParents, UpdateRoleRequest,
},
AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest,
UpdateUserRoleRequest,
};
common_utils::impl_api_event_type!(
Miscellaneous,
(
GetRoleRequest,
GetParentGroupsInfoQueryParams,
AuthorizationInfoResponse,
UpdateUserRoleRequest,
DeleteUserRoleRequest,
CreateRoleRequest,
CreateRoleV2Request,
UpdateRoleRequest,
ListRolesAtEntityLevelRequest,
RoleInfoResponseNew,
RoleInfoWithGroupsResponse,
ListUsersInEntityRequest,
ListRolesQueryParams,
GroupsAndResources,
RoleInfoWithParents,
ParentGroupInfoRequest,
RoleInfoResponseWithParentsGroup,
ListRolesResponse
)
);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/payouts.rs | crates/api_models/src/events/payouts.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::payouts::{
PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutLinkInitiateRequest,
PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListFiltersV2,
PayoutListResponse, PayoutRetrieveRequest, PayoutsAggregateResponse,
PayoutsManualUpdateRequest, PayoutsManualUpdateResponse,
};
impl ApiEventMetric for PayoutRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payout {
payout_id: self.payout_id.to_owned(),
})
}
}
impl ApiEventMetric for PayoutCreateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.payout_id.as_ref().map(|id| ApiEventsType::Payout {
payout_id: id.to_owned(),
})
}
}
impl ApiEventMetric for PayoutCreateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payout {
payout_id: self.payout_id.to_owned(),
})
}
}
impl ApiEventMetric for PayoutActionRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payout {
payout_id: self.payout_id.to_owned(),
})
}
}
impl ApiEventMetric for PayoutListConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PayoutListFilterConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PayoutListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PayoutListFilters {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PayoutListFiltersV2 {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PayoutLinkInitiateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payout {
payout_id: self.payout_id.to_owned(),
})
}
}
impl ApiEventMetric for PayoutsAggregateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PayoutsManualUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payout {
payout_id: self.payout_id.to_owned(),
})
}
}
impl ApiEventMetric for PayoutsManualUpdateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payout {
payout_id: self.payout_id.to_owned(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/payment.rs | crates/api_models/src/events/payment.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
#[cfg(feature = "v2")]
use super::{
PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest,
PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest,
RecoveryPaymentListResponse, RecoveryPaymentsCreate, RecoveryPaymentsResponse,
RevenueRecoveryGetIntentResponse,
};
#[cfg(feature = "v2")]
use crate::payment_methods::{
ListMethodsForPaymentMethodsRequest, PaymentMethodListResponseForSession,
};
use crate::{
payment_methods::{
self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,
PaymentMethodCollectLinkResponse, PaymentMethodMigrateResponse, PaymentMethodResponse,
PaymentMethodUpdate,
},
payments::{
self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,
PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse,
RedirectionResponse,
},
};
#[cfg(feature = "v1")]
use crate::{
payment_methods::{
CustomerPaymentMethodUpdateResponse, PaymentMethodListRequest, PaymentMethodListResponse,
},
payments::{
ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints,
PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,
PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,
PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,
PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
PaymentsManualUpdateRequest, PaymentsManualUpdateResponse,
PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest,
PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest,
PaymentsUpdateMetadataResponse,
},
};
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self.resource_id {
PaymentIdType::PaymentIntentId(ref id) => Some(ApiEventsType::Payment {
payment_id: id.clone(),
}),
_ => None,
}
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsStartRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCaptureRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.to_owned(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCompleteAuthorizeRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsPostSessionTokensRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsUpdateMetadataRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsUpdateMetadataResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsPostSessionTokensResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCancelRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCancelPostCaptureRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExtendAuthorizationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsApproveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRejectRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self.payment_id {
Some(PaymentIdType::PaymentIntentId(ref id)) => Some(ApiEventsType::Payment {
payment_id: id.clone(),
}),
_ => None,
}
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsEligibilityRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsEligibilityResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsCreateIntentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::CheckAndApplyPaymentMethodDataResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsGetIntentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentAttemptListRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_intent_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentAttemptListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsIntentResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
impl ApiEventMetric for RevenueRecoveryGetIntentResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCancelRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCancelResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for PaymentMethodResponse {
#[cfg(feature = "v1")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
})
}
#[cfg(feature = "v2")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerPaymentMethodUpdateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
})
}
}
impl ApiEventMetric for PaymentMethodMigrateResponse {
#[cfg(feature = "v1")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_response.payment_method_id.clone(),
payment_method: self.payment_method_response.payment_method,
payment_method_type: self.payment_method_response.payment_method_type,
})
}
#[cfg(feature = "v2")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_response.id.clone(),
payment_method_type: self.payment_method_response.payment_method_type,
payment_method_subtype: self.payment_method_response.payment_method_subtype,
})
}
}
impl ApiEventMetric for PaymentMethodUpdate {}
#[cfg(feature = "v1")]
impl ApiEventMetric for payment_methods::DefaultPaymentMethod {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: None,
payment_method_type: None,
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: None,
payment_method_subtype: None,
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: None,
payment_method_type: None,
})
}
}
impl ApiEventMetric for payment_methods::CustomerPaymentMethodsListResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentMethodListRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodList {
payment_id: self
.client_secret
.as_ref()
.and_then(|cs| cs.rsplit_once("_secret_"))
.map(|(pid, _)| pid.to_string()),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for ListMethodsForPaymentMethodsRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodList {
payment_id: self
.client_secret
.as_ref()
.and_then(|cs| cs.rsplit_once("_secret_"))
.map(|(pid, _)| pid.to_string()),
})
}
}
impl ApiEventMetric for ListCountriesCurrenciesRequest {}
impl ApiEventMetric for ListCountriesCurrenciesResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentMethodListResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(),
payment_method: Some(self.payment_method),
payment_method_type: self.payment_method_type,
})
}
}
impl ApiEventMetric for PaymentMethodCollectLinkRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.pm_collect_link_id
.as_ref()
.map(|id| ApiEventsType::PaymentMethodCollectLink {
link_id: id.clone(),
})
}
}
impl ApiEventMetric for PaymentMethodCollectLinkRenderRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodCollectLink {
link_id: self.pm_collect_link_id.clone(),
})
}
}
impl ApiEventMetric for PaymentMethodCollectLinkResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodCollectLink {
link_id: self.pm_collect_link_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentListFilterConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListFilters {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListFiltersV2 {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentsCreate {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentListResponseV2 {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentsAggregateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for RedirectionResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExternalAuthenticationResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExternalAuthenticationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for ExtendedCardInfoResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsManualUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsManualUpdateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for PaymentsSessionResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentStartRedirectionRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentMethodListResponseForPayments {
// Payment id would be populated by the request
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodListResponseForSession {}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCaptureResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/chat.rs | crates/api_models/src/events/chat.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::chat::{ChatListRequest, ChatListResponse, ChatRequest, ChatResponse};
common_utils::impl_api_event_type!(
Chat,
(ChatRequest, ChatResponse, ChatListRequest, ChatListResponse)
);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/gsm.rs | crates/api_models/src/events/gsm.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::gsm;
impl ApiEventMetric for gsm::GsmCreateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmDeleteRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/customer.rs | crates/api_models/src/events/customer.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::customers::{
CustomerDeleteResponse, CustomerListRequestWithConstraints, CustomerListResponse,
CustomerRequest, CustomerResponse, CustomerUpdateRequestInternal,
};
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
customer_id: self.customer_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for CustomerDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
customer_id: Some(self.id.clone()),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.get_merchant_reference_id()
.clone()
.map(|cid| ApiEventsType::Customer { customer_id: cid })
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for CustomerRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer { customer_id: None })
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.get_merchant_reference_id()
.clone()
.map(|cid| ApiEventsType::Customer { customer_id: cid })
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for CustomerResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
customer_id: Some(self.id.clone()),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerUpdateRequestInternal {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
customer_id: self.customer_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for CustomerUpdateRequestInternal {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
customer_id: Some(self.id.clone()),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerListRequestWithConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
customer_id: self.customer_id.clone()?,
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for CustomerListRequestWithConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer { customer_id: None })
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for CustomerListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for CustomerListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/recon.rs | crates/api_models/src/events/recon.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use masking::PeekInterface;
use crate::recon::{
ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest, VerifyTokenResponse,
};
impl ApiEventMetric for ReconUpdateMerchantRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Recon)
}
}
impl ApiEventMetric for ReconTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Recon)
}
}
impl ApiEventMetric for ReconStatusResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Recon)
}
}
impl ApiEventMetric for VerifyTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::User {
user_id: self.user_email.peek().to_string(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/refund.rs | crates/api_models/src/events/refund.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::refunds::{
self, RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest,
RefundListResponse,
};
#[cfg(feature = "v1")]
use crate::refunds::{
RefundManualUpdateRequest, RefundRequest, RefundUpdateRequest, RefundsRetrieveRequest,
};
#[cfg(feature = "v1")]
impl ApiEventMetric for RefundRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
let payment_id = self.payment_id.clone();
self.refund_id
.clone()
.map(|refund_id| ApiEventsType::Refund {
payment_id: Some(payment_id),
refund_id,
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for refunds::RefundResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for refunds::RefundResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for RefundsRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Refund {
payment_id: None,
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for refunds::RefundsRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Refund {
payment_id: None,
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for RefundUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Refund {
payment_id: None,
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for RefundManualUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Refund {
payment_id: None,
refund_id: self.refund_id.clone(),
})
}
}
impl ApiEventMetric for RefundListRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for RefundListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for RefundAggregateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for RefundListMetaData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for RefundListFilters {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/locker_migration.rs | crates/api_models/src/events/locker_migration.rs | use common_utils::events::ApiEventMetric;
use crate::locker_migration::MigrateCardResponse;
impl ApiEventMetric for MigrateCardResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::RustLocker)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/events/external_service_auth.rs | crates/api_models/src/events/external_service_auth.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::external_service_auth::{
ExternalSignoutTokenRequest, ExternalTokenResponse, ExternalVerifyTokenRequest,
ExternalVerifyTokenResponse,
};
impl ApiEventMetric for ExternalTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
impl ApiEventMetric for ExternalVerifyTokenRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
impl ApiEventMetric for ExternalVerifyTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
impl ApiEventMetric for ExternalSignoutTokenRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/outgoing_webhook_event.rs | crates/api_models/src/analytics/outgoing_webhook_event.rs | #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct OutgoingWebhookLogsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub event_id: Option<String>,
pub refund_id: Option<String>,
pub dispute_id: Option<String>,
pub mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub attempt_id: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/auth_events.rs | crates/api_models/src/analytics/auth_events.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_enums::{
AuthenticationConnectors, AuthenticationStatus, Currency, DecoupledAuthenticationType,
TransactionStatus,
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct AuthEventFilters {
#[serde(default)]
pub authentication_status: Vec<AuthenticationStatus>,
#[serde(default)]
pub trans_status: Vec<TransactionStatus>,
#[serde(default)]
pub authentication_type: Vec<DecoupledAuthenticationType>,
#[serde(default)]
pub error_message: Vec<String>,
#[serde(default)]
pub authentication_connector: Vec<AuthenticationConnectors>,
#[serde(default)]
pub message_version: Vec<String>,
#[serde(default)]
pub platform: Vec<String>,
#[serde(default)]
pub acs_reference_number: Vec<String>,
#[serde(default)]
pub mcc: Vec<String>,
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub merchant_country: Vec<String>,
#[serde(default)]
pub billing_country: Vec<String>,
#[serde(default)]
pub shipping_country: Vec<String>,
#[serde(default)]
pub issuer_country: Vec<String>,
#[serde(default)]
pub earliest_supported_version: Vec<String>,
#[serde(default)]
pub latest_supported_version: Vec<String>,
#[serde(default)]
pub whitelist_decision: Vec<bool>,
#[serde(default)]
pub device_manufacturer: Vec<String>,
#[serde(default)]
pub device_type: Vec<String>,
#[serde(default)]
pub device_brand: Vec<String>,
#[serde(default)]
pub device_os: Vec<String>,
#[serde(default)]
pub device_display: Vec<String>,
#[serde(default)]
pub browser_name: Vec<String>,
#[serde(default)]
pub browser_version: Vec<String>,
#[serde(default)]
pub issuer_id: Vec<String>,
#[serde(default)]
pub scheme_name: Vec<String>,
#[serde(default)]
pub exemption_requested: Vec<bool>,
#[serde(default)]
pub exemption_accepted: Vec<bool>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthEventDimensions {
AuthenticationStatus,
#[strum(serialize = "trans_status")]
#[serde(rename = "trans_status")]
TransactionStatus,
AuthenticationType,
ErrorMessage,
AuthenticationConnector,
MessageVersion,
AcsReferenceNumber,
Platform,
Mcc,
Currency,
MerchantCountry,
BillingCountry,
ShippingCountry,
IssuerCountry,
EarliestSupportedVersion,
LatestSupportedVersion,
WhitelistDecision,
DeviceManufacturer,
DeviceType,
DeviceBrand,
DeviceOs,
DeviceDisplay,
BrowserName,
BrowserVersion,
IssuerId,
SchemeName,
ExemptionRequested,
ExemptionAccepted,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum AuthEventMetrics {
AuthenticationCount,
AuthenticationAttemptCount,
AuthenticationSuccessCount,
ChallengeFlowCount,
FrictionlessFlowCount,
FrictionlessSuccessCount,
ChallengeAttemptCount,
ChallengeSuccessCount,
AuthenticationErrorMessage,
AuthenticationFunnel,
AuthenticationExemptionApprovedCount,
AuthenticationExemptionRequestedCount,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
pub enum AuthEventFlows {
IncomingWebhookReceive,
PaymentsExternalAuthentication,
}
pub mod metric_behaviour {
pub struct AuthenticationCount;
pub struct AuthenticationAttemptCount;
pub struct AuthenticationSuccessCount;
pub struct ChallengeFlowCount;
pub struct FrictionlessFlowCount;
pub struct FrictionlessSuccessCount;
pub struct ChallengeAttemptCount;
pub struct ChallengeSuccessCount;
pub struct AuthenticationErrorMessage;
pub struct AuthenticationFunnel;
}
impl From<AuthEventMetrics> for NameDescription {
fn from(value: AuthEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<AuthEventDimensions> for NameDescription {
fn from(value: AuthEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct AuthEventMetricsBucketIdentifier {
pub authentication_status: Option<AuthenticationStatus>,
pub trans_status: Option<TransactionStatus>,
pub authentication_type: Option<DecoupledAuthenticationType>,
pub error_message: Option<String>,
pub authentication_connector: Option<AuthenticationConnectors>,
pub message_version: Option<String>,
pub acs_reference_number: Option<String>,
pub mcc: Option<String>,
pub currency: Option<Currency>,
pub merchant_country: Option<String>,
pub billing_country: Option<String>,
pub shipping_country: Option<String>,
pub issuer_country: Option<String>,
pub earliest_supported_version: Option<String>,
pub latest_supported_version: Option<String>,
pub whitelist_decision: Option<bool>,
pub device_manufacturer: Option<String>,
pub device_type: Option<String>,
pub device_brand: Option<String>,
pub device_os: Option<String>,
pub device_display: Option<String>,
pub browser_name: Option<String>,
pub browser_version: Option<String>,
pub issuer_id: Option<String>,
pub scheme_name: Option<String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl AuthEventMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
authentication_status: Option<AuthenticationStatus>,
trans_status: Option<TransactionStatus>,
authentication_type: Option<DecoupledAuthenticationType>,
error_message: Option<String>,
authentication_connector: Option<AuthenticationConnectors>,
message_version: Option<String>,
acs_reference_number: Option<String>,
mcc: Option<String>,
currency: Option<Currency>,
merchant_country: Option<String>,
billing_country: Option<String>,
shipping_country: Option<String>,
issuer_country: Option<String>,
earliest_supported_version: Option<String>,
latest_supported_version: Option<String>,
whitelist_decision: Option<bool>,
device_manufacturer: Option<String>,
device_type: Option<String>,
device_brand: Option<String>,
device_os: Option<String>,
device_display: Option<String>,
browser_name: Option<String>,
browser_version: Option<String>,
issuer_id: Option<String>,
scheme_name: Option<String>,
exemption_requested: Option<bool>,
exemption_accepted: Option<bool>,
normalized_time_range: TimeRange,
) -> Self {
Self {
authentication_status,
trans_status,
authentication_type,
error_message,
authentication_connector,
message_version,
acs_reference_number,
mcc,
currency,
merchant_country,
billing_country,
shipping_country,
issuer_country,
earliest_supported_version,
latest_supported_version,
whitelist_decision,
device_manufacturer,
device_type,
device_brand,
device_os,
device_display,
browser_name,
browser_version,
issuer_id,
scheme_name,
exemption_requested,
exemption_accepted,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for AuthEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.authentication_status.hash(state);
self.trans_status.hash(state);
self.authentication_type.hash(state);
self.authentication_connector.hash(state);
self.message_version.hash(state);
self.acs_reference_number.hash(state);
self.error_message.hash(state);
self.mcc.hash(state);
self.currency.hash(state);
self.merchant_country.hash(state);
self.billing_country.hash(state);
self.shipping_country.hash(state);
self.issuer_country.hash(state);
self.earliest_supported_version.hash(state);
self.latest_supported_version.hash(state);
self.whitelist_decision.hash(state);
self.device_manufacturer.hash(state);
self.device_type.hash(state);
self.device_brand.hash(state);
self.device_os.hash(state);
self.device_display.hash(state);
self.browser_name.hash(state);
self.browser_version.hash(state);
self.issuer_id.hash(state);
self.scheme_name.hash(state);
self.exemption_requested.hash(state);
self.exemption_accepted.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for AuthEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct AuthEventMetricsBucketValue {
pub authentication_count: Option<u64>,
pub authentication_attempt_count: Option<u64>,
pub authentication_success_count: Option<u64>,
pub challenge_flow_count: Option<u64>,
pub challenge_attempt_count: Option<u64>,
pub challenge_success_count: Option<u64>,
pub frictionless_flow_count: Option<u64>,
pub frictionless_success_count: Option<u64>,
pub error_message_count: Option<u64>,
pub authentication_funnel: Option<u64>,
pub authentication_exemption_approved_count: Option<u64>,
pub authentication_exemption_requested_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: AuthEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: AuthEventMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/refunds.rs | crates/api_models/src/analytics/refunds.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use crate::enums::{Currency, RefundStatus};
#[derive(
Clone,
Copy,
Debug,
Hash,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
// TODO RefundType api_models_oss need to mapped to storage_model
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RefundType {
InstantRefund,
RegularRefund,
RetryRefund,
}
use super::{ForexMetric, NameDescription, TimeRange};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct RefundFilters {
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub refund_status: Vec<RefundStatus>,
#[serde(default)]
pub connector: Vec<String>,
#[serde(default)]
pub refund_type: Vec<RefundType>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub refund_reason: Vec<String>,
#[serde(default)]
pub refund_error_message: Vec<String>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RefundDimensions {
Currency,
RefundStatus,
Connector,
RefundType,
ProfileId,
RefundReason,
RefundErrorMessage,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundMetrics {
RefundSuccessRate,
RefundCount,
RefundSuccessCount,
RefundProcessedAmount,
SessionizedRefundSuccessRate,
SessionizedRefundCount,
SessionizedRefundSuccessCount,
SessionizedRefundProcessedAmount,
SessionizedRefundReason,
SessionizedRefundErrorMessage,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ReasonsResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorMessagesResult {
pub error_message: String,
pub count: i64,
pub percentage: f64,
}
#[derive(
Clone,
Copy,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundDistributions {
#[strum(serialize = "refund_reason")]
SessionizedRefundReason,
#[strum(serialize = "refund_error_message")]
SessionizedRefundErrorMessage,
}
impl ForexMetric for RefundMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount
)
}
}
pub mod metric_behaviour {
pub struct RefundSuccessRate;
pub struct RefundCount;
pub struct RefundSuccessCount;
pub struct RefundProcessedAmount;
}
impl From<RefundMetrics> for NameDescription {
fn from(value: RefundMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<RefundDimensions> for NameDescription {
fn from(value: RefundDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct RefundMetricsBucketIdentifier {
pub currency: Option<Currency>,
pub refund_status: Option<String>,
pub connector: Option<String>,
pub refund_type: Option<String>,
pub profile_id: Option<String>,
pub refund_reason: Option<String>,
pub refund_error_message: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl Hash for RefundMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.currency.hash(state);
self.refund_status.hash(state);
self.connector.hash(state);
self.refund_type.hash(state);
self.profile_id.hash(state);
self.refund_reason.hash(state);
self.refund_error_message.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for RefundMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
impl RefundMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
currency: Option<Currency>,
refund_status: Option<String>,
connector: Option<String>,
refund_type: Option<String>,
profile_id: Option<String>,
refund_reason: Option<String>,
refund_error_message: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
currency,
refund_status,
connector,
refund_type,
profile_id,
refund_reason,
refund_error_message,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketValue {
pub successful_refunds: Option<u32>,
pub total_refunds: Option<u32>,
pub refund_success_rate: Option<f64>,
pub refund_count: Option<u64>,
pub refund_success_count: Option<u64>,
pub refund_processed_amount: Option<u64>,
pub refund_processed_amount_in_usd: Option<u64>,
pub refund_processed_count: Option<u64>,
pub refund_reason_distribution: Option<Vec<ReasonsResult>>,
pub refund_error_message_distribution: Option<Vec<ErrorMessagesResult>>,
pub refund_reason_count: Option<u64>,
pub refund_error_message_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketResponse {
#[serde(flatten)]
pub values: RefundMetricsBucketValue,
#[serde(flatten)]
pub dimensions: RefundMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/routing_events.rs | crates/api_models/src/analytics/routing_events.rs | #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingEventsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub refund_id: Option<String>,
pub dispute_id: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/sdk_events.rs | crates/api_models/src/analytics/sdk_events.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkEventsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub time_range: TimeRange,
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SdkEventFilters {
#[serde(default)]
pub payment_method: Vec<String>,
#[serde(default)]
pub platform: Vec<String>,
#[serde(default)]
pub browser_name: Vec<String>,
#[serde(default)]
pub source: Vec<String>,
#[serde(default)]
pub component: Vec<String>,
#[serde(default)]
pub payment_experience: Vec<String>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum SdkEventDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
PaymentMethod,
Platform,
BrowserName,
Source,
Component,
PaymentExperience,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum SdkEventMetrics {
PaymentAttempts,
PaymentMethodsCallCount,
SdkRenderedCount,
SdkInitiatedCount,
PaymentMethodSelectedCount,
PaymentDataFilledCount,
AveragePaymentTime,
LoadTime,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SdkEventNames {
OrcaElementsCalled,
AppRendered,
PaymentMethodChanged,
PaymentDataFilled,
PaymentAttempt,
PaymentMethodsCall,
ConfirmCall,
SessionsCall,
CustomerPaymentMethodsCall,
RedirectingUser,
DisplayBankTransferInfoPage,
DisplayQrCodeInfoPage,
AuthenticationCall,
AuthenticationCallInit,
ThreeDsMethodCall,
ThreeDsMethodResult,
ThreeDsMethod,
LoaderChanged,
DisplayThreeDsSdk,
ThreeDsSdkInit,
AreqParamsGeneration,
ChallengePresented,
ChallengeComplete,
}
pub mod metric_behaviour {
pub struct PaymentAttempts;
pub struct PaymentMethodsCallCount;
pub struct SdkRenderedCount;
pub struct SdkInitiatedCount;
pub struct PaymentMethodSelectedCount;
pub struct PaymentDataFilledCount;
pub struct AveragePaymentTime;
pub struct LoadTime;
}
impl From<SdkEventMetrics> for NameDescription {
fn from(value: SdkEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<SdkEventDimensions> for NameDescription {
fn from(value: SdkEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct SdkEventMetricsBucketIdentifier {
pub payment_method: Option<String>,
pub platform: Option<String>,
pub browser_name: Option<String>,
pub source: Option<String>,
pub component: Option<String>,
pub payment_experience: Option<String>,
pub time_bucket: Option<String>,
}
impl SdkEventMetricsBucketIdentifier {
pub fn new(
payment_method: Option<String>,
platform: Option<String>,
browser_name: Option<String>,
source: Option<String>,
component: Option<String>,
payment_experience: Option<String>,
time_bucket: Option<String>,
) -> Self {
Self {
payment_method,
platform,
browser_name,
source,
component,
payment_experience,
time_bucket,
}
}
}
impl Hash for SdkEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.payment_method.hash(state);
self.platform.hash(state);
self.browser_name.hash(state);
self.source.hash(state);
self.component.hash(state);
self.payment_experience.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for SdkEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct SdkEventMetricsBucketValue {
pub payment_attempts: Option<u64>,
pub payment_methods_call_count: Option<u64>,
pub average_payment_time: Option<u64>,
pub load_time: Option<u64>,
pub sdk_rendered_count: Option<u64>,
pub sdk_initiated_count: Option<u64>,
pub payment_method_selected_count: Option<u64>,
pub payment_data_filled_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: SdkEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: SdkEventMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/active_payments.rs | crates/api_models/src/analytics/active_payments.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::NameDescription;
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ActivePaymentsMetrics {
ActivePayments,
}
pub mod metric_behaviour {
pub struct ActivePayments;
}
impl From<ActivePaymentsMetrics> for NameDescription {
fn from(value: ActivePaymentsMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct ActivePaymentsMetricsBucketIdentifier {
pub time_bucket: Option<String>,
}
impl ActivePaymentsMetricsBucketIdentifier {
pub fn new(time_bucket: Option<String>) -> Self {
Self { time_bucket }
}
}
impl Hash for ActivePaymentsMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.time_bucket.hash(state);
}
}
impl PartialEq for ActivePaymentsMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct ActivePaymentsMetricsBucketValue {
pub active_payments: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: ActivePaymentsMetricsBucketValue,
#[serde(flatten)]
pub dimensions: ActivePaymentsMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/disputes.rs | crates/api_models/src/analytics/disputes.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{Currency, DisputeStage};
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum DisputeMetrics {
DisputeStatusMetric,
TotalAmountDisputed,
TotalDisputeLostAmount,
SessionizedDisputeStatusMetric,
SessionizedTotalAmountDisputed,
SessionizedTotalDisputeLostAmount,
}
impl ForexMetric for DisputeMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::TotalAmountDisputed | Self::TotalDisputeLostAmount
)
}
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DisputeDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
DisputeStage,
Currency,
}
impl From<DisputeDimensions> for NameDescription {
fn from(value: DisputeDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<DisputeMetrics> for NameDescription {
fn from(value: DisputeMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct DisputeFilters {
#[serde(default)]
pub dispute_stage: Vec<DisputeStage>,
#[serde(default)]
pub connector: Vec<String>,
#[serde(default)]
pub currency: Vec<Currency>,
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct DisputeMetricsBucketIdentifier {
pub dispute_stage: Option<DisputeStage>,
pub connector: Option<String>,
pub currency: Option<Currency>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl Hash for DisputeMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.dispute_stage.hash(state);
self.connector.hash(state);
self.currency.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for DisputeMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
impl DisputeMetricsBucketIdentifier {
pub fn new(
dispute_stage: Option<DisputeStage>,
connector: Option<String>,
currency: Option<Currency>,
normalized_time_range: TimeRange,
) -> Self {
Self {
dispute_stage,
connector,
currency,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct DisputeMetricsBucketValue {
pub disputes_challenged: Option<u64>,
pub disputes_won: Option<u64>,
pub disputes_lost: Option<u64>,
pub disputed_amount: Option<u64>,
pub dispute_lost_amount: Option<u64>,
pub total_dispute: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct DisputeMetricsBucketResponse {
#[serde(flatten)]
pub values: DisputeMetricsBucketValue,
#[serde(flatten)]
pub dimensions: DisputeMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/connector_events.rs | crates/api_models/src/analytics/connector_events.rs | #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ConnectorEventsRequest {
pub payment_id: common_utils::id_type::PaymentId,
pub refund_id: Option<String>,
pub dispute_id: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/search.rs | crates/api_models/src/analytics/search.rs | use common_utils::{hashing::HashedString, types::TimeRange};
use masking::WithType;
use serde_json::Value;
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
pub currency: Option<Vec<String>>,
pub status: Option<Vec<String>>,
pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>,
pub search_tags: Option<Vec<HashedString<WithType>>>,
pub connector: Option<Vec<String>>,
pub payment_method_type: Option<Vec<String>>,
pub card_network: Option<Vec<String>>,
pub card_last_4: Option<Vec<String>>,
pub payment_id: Option<Vec<String>>,
pub amount: Option<Vec<u64>>,
pub customer_id: Option<Vec<String>>,
}
impl SearchFilters {
pub fn is_all_none(&self) -> bool {
self.payment_method.is_none()
&& self.currency.is_none()
&& self.status.is_none()
&& self.customer_email.is_none()
&& self.search_tags.is_none()
&& self.connector.is_none()
&& self.payment_method_type.is_none()
&& self.card_network.is_none()
&& self.card_last_4.is_none()
&& self.payment_id.is_none()
&& self.amount.is_none()
&& self.customer_id.is_none()
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetGlobalSearchRequest {
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
#[serde(default)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchRequest {
pub offset: i64,
pub count: i64,
pub query: String,
#[serde(default)]
pub filters: Option<SearchFilters>,
#[serde(default)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchRequestWithIndex {
pub index: SearchIndex,
pub search_req: GetSearchRequest,
}
#[derive(
Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy, Eq, PartialEq,
)]
#[serde(rename_all = "snake_case")]
pub enum SearchIndex {
PaymentAttempts,
PaymentIntents,
Refunds,
Disputes,
Payouts,
SessionizerPaymentAttempts,
SessionizerPaymentIntents,
SessionizerRefunds,
SessionizerDisputes,
}
#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)]
pub enum SearchStatus {
Success,
Failure,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSearchResponse {
pub count: u64,
pub index: SearchIndex,
pub hits: Vec<Value>,
pub status: SearchStatus,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpenMsearchOutput {
#[serde(default)]
pub responses: Vec<OpensearchOutput>,
pub error: Option<OpensearchErrorDetails>,
}
#[derive(Debug, serde::Deserialize)]
#[serde(untagged)]
pub enum OpensearchOutput {
Success(OpensearchSuccess),
Error(OpensearchError),
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchError {
pub error: OpensearchErrorDetails,
pub status: u16,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchErrorDetails {
#[serde(rename = "type")]
pub error_type: String,
pub reason: String,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchSuccess {
pub hits: OpensearchHits,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchHits {
pub total: OpensearchResultsTotal,
pub hits: Vec<OpensearchHit>,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchResultsTotal {
pub value: u64,
}
#[derive(Debug, serde::Deserialize)]
pub struct OpensearchHit {
#[serde(rename = "_source")]
pub source: Value,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/payment_intents.rs | crates/api_models/src/analytics/payment_intents.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{
AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType,
};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentIntentFilters {
#[serde(default)]
pub status: Vec<IntentStatus>,
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub connector: Vec<Connector>,
#[serde(default)]
pub auth_type: Vec<AuthenticationType>,
#[serde(default)]
pub payment_method: Vec<PaymentMethod>,
#[serde(default)]
pub payment_method_type: Vec<PaymentMethodType>,
#[serde(default)]
pub card_network: Vec<String>,
#[serde(default)]
pub merchant_id: Vec<id_type::MerchantId>,
#[serde(default)]
pub card_last_4: Vec<String>,
#[serde(default)]
pub card_issuer: Vec<String>,
#[serde(default)]
pub error_reason: Vec<String>,
#[serde(default)]
pub customer_id: Vec<id_type::CustomerId>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentIntentDimensions {
#[strum(serialize = "status")]
#[serde(rename = "status")]
PaymentIntentStatus,
Currency,
ProfileId,
Connector,
#[strum(serialize = "authentication_type")]
#[serde(rename = "authentication_type")]
AuthType,
PaymentMethod,
PaymentMethodType,
CardNetwork,
MerchantId,
#[strum(serialize = "card_last_4")]
#[serde(rename = "card_last_4")]
CardLast4,
CardIssuer,
ErrorReason,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentMetrics {
SuccessfulSmartRetries,
TotalSmartRetries,
SmartRetriedAmount,
PaymentIntentCount,
PaymentsSuccessRate,
PaymentProcessedAmount,
SessionizedSuccessfulSmartRetries,
SessionizedTotalSmartRetries,
SessionizedSmartRetriedAmount,
SessionizedPaymentIntentCount,
SessionizedPaymentsSuccessRate,
SessionizedPaymentProcessedAmount,
SessionizedPaymentsDistribution,
}
impl ForexMetric for PaymentIntentMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::PaymentProcessedAmount
| Self::SmartRetriedAmount
| Self::SessionizedPaymentProcessedAmount
| Self::SessionizedSmartRetriedAmount
)
}
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
pub mod metric_behaviour {
pub struct SuccessfulSmartRetries;
pub struct TotalSmartRetries;
pub struct SmartRetriedAmount;
pub struct PaymentIntentCount;
pub struct PaymentsSuccessRate;
}
impl From<PaymentIntentMetrics> for NameDescription {
fn from(value: PaymentIntentMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<PaymentIntentDimensions> for NameDescription {
fn from(value: PaymentIntentDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct PaymentIntentMetricsBucketIdentifier {
pub status: Option<IntentStatus>,
pub currency: Option<Currency>,
pub profile_id: Option<String>,
pub connector: Option<String>,
pub auth_type: Option<AuthenticationType>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl PaymentIntentMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
status: Option<IntentStatus>,
currency: Option<Currency>,
profile_id: Option<String>,
connector: Option<String>,
auth_type: Option<AuthenticationType>,
payment_method: Option<String>,
payment_method_type: Option<String>,
card_network: Option<String>,
merchant_id: Option<String>,
card_last_4: Option<String>,
card_issuer: Option<String>,
error_reason: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
status,
currency,
profile_id,
connector,
auth_type,
payment_method,
payment_method_type,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for PaymentIntentMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.status.map(|i| i.to_string()).hash(state);
self.currency.hash(state);
self.profile_id.hash(state);
self.connector.hash(state);
self.auth_type.map(|i| i.to_string()).hash(state);
self.payment_method.hash(state);
self.payment_method_type.hash(state);
self.card_network.hash(state);
self.merchant_id.hash(state);
self.card_last_4.hash(state);
self.card_issuer.hash(state);
self.error_reason.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for PaymentIntentMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentIntentMetricsBucketValue {
pub successful_smart_retries: Option<u64>,
pub total_smart_retries: Option<u64>,
pub smart_retried_amount: Option<u64>,
pub smart_retried_amount_in_usd: Option<u64>,
pub smart_retried_amount_without_smart_retries: Option<u64>,
pub smart_retried_amount_without_smart_retries_in_usd: Option<u64>,
pub payment_intent_count: Option<u64>,
pub successful_payments: Option<u32>,
pub successful_payments_without_smart_retries: Option<u32>,
pub total_payments: Option<u32>,
pub payments_success_rate: Option<f64>,
pub payments_success_rate_without_smart_retries: Option<f64>,
pub payment_processed_amount: Option<u64>,
pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_in_usd: Option<u64>,
pub payment_processed_count_without_smart_retries: Option<u64>,
pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: PaymentIntentMetricsBucketValue,
#[serde(flatten)]
pub dimensions: PaymentIntentMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/frm.rs | crates/api_models/src/analytics/frm.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_enums::enums::FraudCheckStatus;
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FrmTransactionType {
#[default]
PreFrm,
PostFrm,
}
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct FrmFilters {
#[serde(default)]
pub frm_status: Vec<FraudCheckStatus>,
#[serde(default)]
pub frm_name: Vec<String>,
#[serde(default)]
pub frm_transaction_type: Vec<FrmTransactionType>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FrmDimensions {
FrmStatus,
FrmName,
FrmTransactionType,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum FrmMetrics {
FrmTriggeredAttempts,
FrmBlockedRate,
}
pub mod metric_behaviour {
pub struct FrmTriggeredAttempts;
pub struct FrmBlockRate;
}
impl From<FrmMetrics> for NameDescription {
fn from(value: FrmMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<FrmDimensions> for NameDescription {
fn from(value: FrmDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct FrmMetricsBucketIdentifier {
pub frm_status: Option<String>,
pub frm_name: Option<String>,
pub frm_transaction_type: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl Hash for FrmMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.frm_status.hash(state);
self.frm_name.hash(state);
self.frm_transaction_type.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for FrmMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
impl FrmMetricsBucketIdentifier {
pub fn new(
frm_status: Option<String>,
frm_name: Option<String>,
frm_transaction_type: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
frm_status,
frm_name,
frm_transaction_type,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct FrmMetricsBucketValue {
pub frm_triggered_attempts: Option<u64>,
pub frm_blocked_rate: Option<f64>,
}
#[derive(Debug, serde::Serialize)]
pub struct FrmMetricsBucketResponse {
#[serde(flatten)]
pub values: FrmMetricsBucketValue,
#[serde(flatten)]
pub dimensions: FrmMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/api_event.rs | crates/api_models/src/analytics/api_event.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApiLogsRequest {
#[serde(flatten)]
pub query_param: QueryType,
}
pub enum FilterType {
ApiCountFilter,
LatencyFilter,
StatusCodeFilter,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(tag = "type")]
pub enum QueryType {
Payment {
payment_id: common_utils::id_type::PaymentId,
},
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
},
Dispute {
payment_id: common_utils::id_type::PaymentId,
dispute_id: String,
},
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ApiEventDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
StatusCode,
FlowType,
ApiFlow,
}
impl From<ApiEventDimensions> for NameDescription {
fn from(value: ApiEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct ApiEventFilters {
pub status_code: Vec<u64>,
pub flow_type: Vec<String>,
pub api_flow: Vec<String>,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ApiEventMetrics {
Latency,
ApiCount,
StatusCodeCount,
}
impl From<ApiEventMetrics> for NameDescription {
fn from(value: ApiEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct ApiEventMetricsBucketIdentifier {
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
// Coz FE sucks
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl ApiEventMetricsBucketIdentifier {
pub fn new(normalized_time_range: TimeRange) -> Self {
Self {
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for ApiEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.time_bucket.hash(state);
}
}
impl PartialEq for ApiEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct ApiEventMetricsBucketValue {
pub latency: Option<u64>,
pub api_count: Option<u64>,
pub status_code_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct ApiMetricsBucketResponse {
#[serde(flatten)]
pub values: ApiEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: ApiEventMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/analytics/payments.rs | crates/api_models/src/analytics/payments.rs | use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{
AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod,
PaymentMethodType, RoutingApproach,
};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentFilters {
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub status: Vec<AttemptStatus>,
#[serde(default)]
pub connector: Vec<Connector>,
#[serde(default)]
pub auth_type: Vec<AuthenticationType>,
#[serde(default)]
pub payment_method: Vec<PaymentMethod>,
#[serde(default)]
pub payment_method_type: Vec<PaymentMethodType>,
#[serde(default)]
pub client_source: Vec<String>,
#[serde(default)]
pub client_version: Vec<String>,
#[serde(default)]
pub card_network: Vec<CardNetwork>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub merchant_id: Vec<id_type::MerchantId>,
#[serde(default)]
pub card_last_4: Vec<String>,
#[serde(default)]
pub card_issuer: Vec<String>,
#[serde(default)]
pub error_reason: Vec<String>,
#[serde(default)]
pub first_attempt: Vec<bool>,
#[serde(default)]
pub routing_approach: Vec<RoutingApproach>,
#[serde(default)]
pub signature_network: Vec<String>,
#[serde(default)]
pub is_issuer_regulated: Vec<bool>,
#[serde(default)]
pub is_debit_routed: Vec<bool>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
PaymentMethod,
PaymentMethodType,
Currency,
#[strum(serialize = "authentication_type")]
#[serde(rename = "authentication_type")]
AuthType,
#[strum(serialize = "status")]
#[serde(rename = "status")]
PaymentStatus,
ClientSource,
ClientVersion,
ProfileId,
CardNetwork,
MerchantId,
#[strum(serialize = "card_last_4")]
#[serde(rename = "card_last_4")]
CardLast4,
CardIssuer,
ErrorReason,
RoutingApproach,
SignatureNetwork,
IsIssuerRegulated,
IsDebitRouted,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentMetrics {
PaymentSuccessRate,
PaymentCount,
PaymentSuccessCount,
PaymentProcessedAmount,
AvgTicketSize,
RetriesCount,
ConnectorSuccessRate,
DebitRouting,
SessionizedPaymentSuccessRate,
SessionizedPaymentCount,
SessionizedPaymentSuccessCount,
SessionizedPaymentProcessedAmount,
SessionizedAvgTicketSize,
SessionizedRetriesCount,
SessionizedConnectorSuccessRate,
SessionizedDebitRouting,
PaymentsDistribution,
FailureReasons,
}
impl ForexMetric for PaymentMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::PaymentProcessedAmount
| Self::AvgTicketSize
| Self::DebitRouting
| Self::SessionizedPaymentProcessedAmount
| Self::SessionizedAvgTicketSize
| Self::SessionizedDebitRouting,
)
}
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
#[derive(
Clone,
Copy,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentDistributions {
#[strum(serialize = "error_message")]
PaymentErrorMessage,
}
pub mod metric_behaviour {
pub struct PaymentSuccessRate;
pub struct PaymentCount;
pub struct PaymentSuccessCount;
pub struct PaymentProcessedAmount;
pub struct AvgTicketSize;
}
impl From<PaymentMetrics> for NameDescription {
fn from(value: PaymentMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<PaymentDimensions> for NameDescription {
fn from(value: PaymentDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct PaymentMetricsBucketIdentifier {
pub currency: Option<Currency>,
pub status: Option<AttemptStatus>,
pub connector: Option<String>,
#[serde(rename = "authentication_type")]
pub auth_type: Option<AuthenticationType>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
pub routing_approach: Option<RoutingApproach>,
pub signature_network: Option<String>,
pub is_issuer_regulated: Option<bool>,
pub is_debit_routed: Option<bool>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
// Coz FE sucks
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl PaymentMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
currency: Option<Currency>,
status: Option<AttemptStatus>,
connector: Option<String>,
auth_type: Option<AuthenticationType>,
payment_method: Option<String>,
payment_method_type: Option<String>,
client_source: Option<String>,
client_version: Option<String>,
profile_id: Option<String>,
card_network: Option<String>,
merchant_id: Option<String>,
card_last_4: Option<String>,
card_issuer: Option<String>,
error_reason: Option<String>,
routing_approach: Option<RoutingApproach>,
signature_network: Option<String>,
is_issuer_regulated: Option<bool>,
is_debit_routed: Option<bool>,
normalized_time_range: TimeRange,
) -> Self {
Self {
currency,
status,
connector,
auth_type,
payment_method,
payment_method_type,
client_source,
client_version,
profile_id,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
routing_approach,
signature_network,
is_issuer_regulated,
is_debit_routed,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for PaymentMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.currency.hash(state);
self.status.map(|i| i.to_string()).hash(state);
self.connector.hash(state);
self.auth_type.map(|i| i.to_string()).hash(state);
self.payment_method.hash(state);
self.payment_method_type.hash(state);
self.client_source.hash(state);
self.client_version.hash(state);
self.profile_id.hash(state);
self.card_network.hash(state);
self.merchant_id.hash(state);
self.card_last_4.hash(state);
self.card_issuer.hash(state);
self.error_reason.hash(state);
self.routing_approach
.clone()
.map(|i| i.to_string())
.hash(state);
self.signature_network.hash(state);
self.is_issuer_regulated.hash(state);
self.is_debit_routed.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for PaymentMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentMetricsBucketValue {
pub payment_success_rate: Option<f64>,
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub payment_processed_count_without_smart_retries: Option<u64>,
pub avg_ticket_size: Option<f64>,
pub payment_error_message: Option<Vec<ErrorResult>>,
pub retries_count: Option<u64>,
pub retries_amount_processed: Option<u64>,
pub connector_success_rate: Option<f64>,
pub payments_success_rate_distribution: Option<f64>,
pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
pub payments_success_rate_distribution_with_only_retries: Option<f64>,
pub payments_failure_rate_distribution: Option<f64>,
pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
pub payments_failure_rate_distribution_with_only_retries: Option<f64>,
pub failure_reason_count: Option<u64>,
pub failure_reason_count_without_smart_retries: Option<u64>,
pub debit_routed_transaction_count: Option<u64>,
pub debit_routing_savings: Option<u64>,
pub debit_routing_savings_in_usd: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: PaymentMetricsBucketValue,
#[serde(flatten)]
pub dimensions: PaymentMetricsBucketIdentifier,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/build.rs | crates/external_services/build.rs | fn main() -> Result<(), Box<dyn std::error::Error>> {
// Compilation for revenue recovery protos
#[cfg(feature = "revenue_recovery")]
{
let proto_base_path = router_env::workspace_path().join("proto");
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
let recovery_proto_files = [proto_base_path.join("recovery_decider.proto")];
#[allow(clippy::expect_used, clippy::unwrap_in_result)]
tonic_build::configure()
.out_dir(&out_dir)
.compile_well_known_types(true)
.extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp")
.compile_protos(&recovery_proto_files, &[&proto_base_path])
.expect("Failed to compile revenue-recovery proto files");
}
// Compilation for dynamic_routing protos
#[cfg(feature = "dynamic_routing")]
{
// Get the directory of the current crate
let proto_path = router_env::workspace_path().join("proto");
let success_rate_proto_file = proto_path.join("success_rate.proto");
let contract_routing_proto_file = proto_path.join("contract_routing.proto");
let elimination_proto_file = proto_path.join("elimination_rate.proto");
let health_check_proto_file = proto_path.join("health_check.proto");
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
// Compile the .proto file
#[allow(clippy::expect_used, clippy::unwrap_in_result)]
tonic_build::configure()
.out_dir(out_dir)
.compile_protos(
&[
success_rate_proto_file,
health_check_proto_file,
elimination_proto_file,
contract_routing_proto_file,
],
&[proto_path],
)
.expect("Failed to compile proto files");
}
Ok(())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/http_client.rs | crates/external_services/src/http_client.rs | use common_utils::{consts, errors::CustomResult, request::Request};
use hyperswitch_interfaces::{errors::HttpClientError, types::Proxy};
use request::{HeaderExt, RequestBuilderExt};
use router_env::{instrument, logger, tracing};
/// client module
pub mod client;
/// metrics module
pub mod metrics;
/// request module
pub mod request;
use std::{error::Error, time::Duration};
use common_utils::request::RequestContent;
pub use common_utils::request::{ContentType, Method, RequestBuilder};
use error_stack::ResultExt;
#[allow(missing_docs)]
#[instrument(skip_all)]
pub async fn send_request(
client_proxy: &Proxy,
request: Request,
option_timeout_secs: Option<u64>,
) -> CustomResult<reqwest::Response, HttpClientError> {
logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request);
let url = url::Url::parse(&request.url).change_context(HttpClientError::UrlParsingFailed)?;
let client = client::create_client(
client_proxy,
request.certificate,
request.certificate_key,
request.ca_certificate,
)?;
let headers = request.headers.construct_header_map()?;
let metrics_tag = router_env::metric_attributes!((
consts::METRICS_HOST_TAG_NAME,
url.host_str().unwrap_or_default().to_owned()
));
let request = {
match request.method {
Method::Get => client.get(url),
Method::Post => {
let client = client.post(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData((form, _))) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(HttpClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Put => {
let client = client.put(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData((form, _))) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(HttpClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Patch => {
let client = client.patch(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData((form, _))) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(HttpClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Delete => client.delete(url),
}
.add_headers(headers)
.timeout(Duration::from_secs(
option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT),
))
};
// We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here.
let cloned_send_request = request.try_clone().map(|cloned_request| async {
cloned_request
.send()
.await
.map_err(|error| match error {
error if error.is_timeout() => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::RequestTimeoutReceived
}
error if is_connection_closed_before_message_could_complete(&error) => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::ConnectionClosedIncompleteMessage
}
_ => HttpClientError::RequestNotSent(error.to_string()),
})
.attach_printable("Unable to send request to connector")
});
let send_request = async {
request
.send()
.await
.map_err(|error| match error {
error if error.is_timeout() => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::RequestTimeoutReceived
}
error if is_connection_closed_before_message_could_complete(&error) => {
metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);
HttpClientError::ConnectionClosedIncompleteMessage
}
_ => HttpClientError::RequestNotSent(error.to_string()),
})
.attach_printable("Unable to send request to connector")
};
let response = common_utils::metrics::utils::record_operation_time(
send_request,
&metrics::EXTERNAL_REQUEST_TIME,
metrics_tag,
)
.await;
// Retry once if the response is connection closed.
//
// This is just due to the racy nature of networking.
// hyper has a connection pool of idle connections, and it selected one to send your request.
// Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool.
// But occasionally, a connection will be selected from the pool
// and written to at the same time the server is deciding to close the connection.
// Since hyper already wrote some of the request,
// it can’t really retry it automatically on a new connection, since the server may have acted already
match response {
Ok(response) => Ok(response),
Err(error)
if error.current_context() == &HttpClientError::ConnectionClosedIncompleteMessage =>
{
metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, metrics_tag);
match cloned_send_request {
Some(cloned_request) => {
logger::info!(
"Retrying request due to connection closed before message could complete"
);
common_utils::metrics::utils::record_operation_time(
cloned_request,
&metrics::EXTERNAL_REQUEST_TIME,
metrics_tag,
)
.await
}
None => {
logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable");
Err(error)
}
}
}
err @ Err(_) => err,
}
}
fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool {
let mut source = error.source();
while let Some(err) = source {
if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() {
if hyper_err.is_incomplete_message() {
return true;
}
}
source = err.source();
}
false
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/no_encryption.rs | crates/external_services/src/no_encryption.rs | //! No encryption functionalities
pub mod core;
pub mod implementers;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/email.rs | crates/external_services/src/email.rs | //! Interactions with the AWS SES SDK
use aws_sdk_sesv2::types::Body;
use common_utils::{errors::CustomResult, pii};
use serde::Deserialize;
/// Implementation of aws ses client
pub mod ses;
/// Implementation of SMTP server client
pub mod smtp;
/// Implementation of Email client when email support is disabled
pub mod no_email;
/// Custom Result type alias for Email operations.
pub type EmailResult<T> = CustomResult<T, EmailError>;
/// A trait that defines the methods that must be implemented to send email.
#[async_trait::async_trait]
pub trait EmailClient: Sync + Send + dyn_clone::DynClone {
/// The rich text type of the email client
type RichText;
/// Sends an email to the specified recipient with the given subject and body.
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
proxy_url: Option<&String>,
) -> EmailResult<()>;
/// Convert Stringified HTML to client native rich text format
/// This has to be done because not all clients may format html as the same
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError>
where
Self::RichText: Send;
}
/// A super trait which is automatically implemented for all EmailClients
#[async_trait::async_trait]
pub trait EmailService: Sync + Send + dyn_clone::DynClone {
/// Compose and send email using the email data
async fn compose_and_send_email(
&self,
base_url: &str,
email_data: Box<dyn EmailData + Send>,
proxy_url: Option<&String>,
) -> EmailResult<()>;
}
#[async_trait::async_trait]
impl<T> EmailService for T
where
T: EmailClient,
<Self as EmailClient>::RichText: Send,
{
async fn compose_and_send_email(
&self,
base_url: &str,
email_data: Box<dyn EmailData + Send>,
proxy_url: Option<&String>,
) -> EmailResult<()> {
let email_data = email_data.get_email_data(base_url);
let email_data = email_data.await?;
let EmailContents {
subject,
body,
recipient,
} = email_data;
let rich_text_string = self.convert_to_rich_text(body)?;
self.send_email(recipient, subject, rich_text_string, proxy_url)
.await
}
}
/// This is a struct used to create Intermediate String for rich text ( html )
#[derive(Debug)]
pub struct IntermediateString(String);
impl IntermediateString {
/// Create a new Instance of IntermediateString using a string
pub fn new(inner: String) -> Self {
Self(inner)
}
/// Get the inner String
pub fn into_inner(self) -> String {
self.0
}
}
/// Temporary output for the email subject
#[derive(Debug)]
pub struct EmailContents {
/// The subject of email
pub subject: String,
/// This will be the intermediate representation of the email body in a generic format.
/// The email clients can convert this intermediate representation to their client specific rich text format
pub body: IntermediateString,
/// The email of the recipient to whom the email has to be sent
pub recipient: pii::Email,
}
/// A trait which will contain the logic of generating the email subject and body
#[async_trait::async_trait]
pub trait EmailData {
/// Get the email contents
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError>;
}
dyn_clone::clone_trait_object!(EmailClient<RichText = Body>);
/// List of available email clients to choose from
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(tag = "active_email_client")]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EmailClientConfigs {
#[default]
/// Default Email client to use when no client is specified
NoEmailClient,
/// AWS ses email client
Ses {
/// AWS SES client configuration
aws_ses: ses::SESConfig,
},
/// Other Simple SMTP server
Smtp {
/// SMTP server configuration
smtp: smtp::SmtpServerConfig,
},
}
/// Struct that contains the settings required to construct an EmailClient.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct EmailSettings {
/// The AWS region to send SES requests to.
pub aws_region: String,
/// Number of days for verification of the email
pub allowed_unverified_days: i64,
/// Sender email
pub sender_email: String,
#[serde(flatten)]
/// The client specific configurations
pub client_config: EmailClientConfigs,
/// Recipient email for recon emails
pub recon_recipient_email: pii::Email,
/// Recipient email for recon emails
pub prod_intent_recipient_email: pii::Email,
}
impl EmailSettings {
/// Validation for the Email client specific configurations
pub fn validate(&self) -> Result<(), &'static str> {
match &self.client_config {
EmailClientConfigs::Ses { ref aws_ses } => aws_ses.validate(),
EmailClientConfigs::Smtp { ref smtp } => smtp.validate(),
EmailClientConfigs::NoEmailClient => Ok(()),
}
}
}
/// Errors that could occur from EmailClient.
#[derive(Debug, thiserror::Error)]
pub enum EmailError {
/// An error occurred when building email client.
#[error("Error building email client")]
ClientBuildingFailure,
/// An error occurred when sending email
#[error("Error sending email to recipient")]
EmailSendingFailure,
/// Failed to generate the email token
#[error("Failed to generate email token")]
TokenGenerationFailure,
/// The expected feature is not implemented
#[error("Feature not implemented")]
NotImplemented,
/// An error occurred when building email content.
#[error("Error building email content")]
ContentBuildFailure,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/lib.rs | crates/external_services/src/lib.rs | //! Interactions with external systems.
#![warn(missing_docs, missing_debug_implementations)]
#[cfg(feature = "aws_kms")]
pub mod aws_kms;
/// crm module
pub mod crm;
#[cfg(feature = "email")]
pub mod email;
pub mod file_storage;
/// Building grpc clients to communicate with the server
pub mod grpc_client;
#[cfg(feature = "hashicorp-vault")]
pub mod hashicorp_vault;
/// http_client module
pub mod http_client;
/// hubspot_proxy module
pub mod hubspot_proxy;
pub mod managers;
pub mod no_encryption;
#[cfg(feature = "superposition")]
pub mod superposition;
/// deserializers module_path
pub mod utils;
#[cfg(feature = "revenue_recovery")]
/// date_time module
pub mod date_time {
use error_stack::ResultExt;
/// Errors in time conversion
#[derive(Debug, thiserror::Error)]
pub enum DateTimeConversionError {
#[error("Invalid timestamp value from prost Timestamp: out of representable range")]
/// Error for out of range
TimestampOutOfRange,
}
/// Converts a `time::PrimitiveDateTime` to a `prost_types::Timestamp`.
pub fn convert_to_prost_timestamp(dt: time::PrimitiveDateTime) -> prost_types::Timestamp {
let odt = dt.assume_utc();
prost_types::Timestamp {
seconds: odt.unix_timestamp(),
// This conversion is safe as nanoseconds (0..999_999_999) always fit within an i32.
#[allow(clippy::as_conversions)]
nanos: odt.nanosecond() as i32,
}
}
/// Converts a `prost_types::Timestamp` to an `time::PrimitiveDateTime`.
pub fn convert_from_prost_timestamp(
ts: &prost_types::Timestamp,
) -> error_stack::Result<time::PrimitiveDateTime, DateTimeConversionError> {
let timestamp_nanos = i128::from(ts.seconds) * 1_000_000_000 + i128::from(ts.nanos);
time::OffsetDateTime::from_unix_timestamp_nanos(timestamp_nanos)
.map(|offset_dt| time::PrimitiveDateTime::new(offset_dt.date(), offset_dt.time()))
.change_context(DateTimeConversionError::TimestampOutOfRange)
}
}
/// Crate specific constants
pub mod consts {
/// General purpose base64 engine
#[cfg(feature = "aws_kms")]
pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose =
base64::engine::general_purpose::STANDARD;
/// Header key used to specify the connector name in UCS requests.
pub(crate) const UCS_HEADER_CONNECTOR: &str = "x-connector";
/// Header key used to indicate the authentication type being used.
pub(crate) const UCS_HEADER_AUTH_TYPE: &str = "x-auth";
/// Header key for sending the API key used for authentication.
pub(crate) const UCS_HEADER_API_KEY: &str = "x-api-key";
/// Header key for sending an additional secret key used in some auth types.
pub(crate) const UCS_HEADER_KEY1: &str = "x-key1";
/// Header key for sending the API secret in signature-based authentication.
pub(crate) const UCS_HEADER_API_SECRET: &str = "x-api-secret";
/// Header key for sending a second additional key used in multi-auth authentication.
pub(crate) const UCS_HEADER_KEY2: &str = "x-key2";
/// Header key for sending the AUTH KEY MAP in currency-based authentication.
pub(crate) const UCS_HEADER_AUTH_KEY_MAP: &str = "x-auth-key-map";
/// Header key for sending the EXTERNAL VAULT METADATA in proxy payments
pub(crate) const UCS_HEADER_EXTERNAL_VAULT_METADATA: &str = "x-external-vault-metadata";
/// Header key for sending the list of lineage ids
pub(crate) const UCS_LINEAGE_IDS: &str = "x-lineage-ids";
/// Header key for sending the merchant reference id to UCS
pub(crate) const UCS_HEADER_REFERENCE_ID: &str = "x-reference-id";
}
/// Metrics for interactions with external systems.
#[cfg(feature = "aws_kms")]
pub mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES");
#[cfg(feature = "aws_kms")]
counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures
#[cfg(feature = "aws_kms")]
counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS decryption time (in sec)
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS encryption time (in sec)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client.rs | crates/external_services/src/grpc_client.rs | /// Dyanimc Routing Client interface implementation
#[cfg(feature = "dynamic_routing")]
pub mod dynamic_routing;
/// gRPC based Heath Check Client interface implementation
#[cfg(feature = "dynamic_routing")]
pub mod health_check_client;
/// gRPC based Recovery Trainer Client interface implementation
#[cfg(feature = "revenue_recovery")]
pub mod revenue_recovery;
/// gRPC based Unified Connector Service Client interface implementation
pub mod unified_connector_service;
use std::{fmt::Debug, sync::Arc};
#[cfg(feature = "dynamic_routing")]
use common_utils::consts;
use common_utils::{id_type, ucs_types};
#[cfg(feature = "dynamic_routing")]
use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy};
#[cfg(feature = "dynamic_routing")]
use health_check_client::HealthCheckClient;
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
use hyper_util::client::legacy::connect::HttpConnector;
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
use router_env::logger;
use router_env::RequestId;
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
use tonic::body::Body;
use typed_builder::TypedBuilder;
#[cfg(feature = "revenue_recovery")]
pub use self::revenue_recovery::{
recovery_decider_client::{
DeciderRequest, DeciderResponse, RecoveryDeciderClientConfig,
RecoveryDeciderClientInterface, RecoveryDeciderError, RecoveryDeciderResult,
},
GrpcRecoveryHeaders,
};
use crate::grpc_client::unified_connector_service::{
UnifiedConnectorServiceClient, UnifiedConnectorServiceClientConfig,
};
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
/// Hyper based Client type for maintaining connection pool for all gRPC services
pub type Client = hyper_util::client::legacy::Client<HttpConnector, Body>;
/// Struct contains all the gRPC Clients
#[derive(Debug, Clone)]
pub struct GrpcClients {
/// The routing client
#[cfg(feature = "dynamic_routing")]
pub dynamic_routing: Option<RoutingStrategy>,
/// Health Check client for all gRPC services
#[cfg(feature = "dynamic_routing")]
pub health_client: HealthCheckClient,
/// Recovery Decider Client
#[cfg(feature = "revenue_recovery")]
pub recovery_decider_client: Option<Box<dyn RecoveryDeciderClientInterface>>,
/// Unified Connector Service client
pub unified_connector_service_client: Option<UnifiedConnectorServiceClient>,
}
/// Type that contains the configs required to construct a gRPC client with its respective services.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
pub struct GrpcClientSettings {
#[cfg(feature = "dynamic_routing")]
/// Configs for Dynamic Routing Client
pub dynamic_routing_client: Option<DynamicRoutingClientConfig>,
#[cfg(feature = "revenue_recovery")]
/// Configs for Recovery Decider Client
pub recovery_decider_client: Option<RecoveryDeciderClientConfig>,
/// Configs for Unified Connector Service client
pub unified_connector_service: Option<UnifiedConnectorServiceClientConfig>,
}
impl GrpcClientSettings {
/// # Panics
///
/// This function will panic if it fails to establish a connection with the gRPC server.
/// This function will be called at service startup.
#[allow(clippy::expect_used)]
pub async fn get_grpc_client_interface(&self) -> Arc<GrpcClients> {
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
let client =
hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
.http2_only(true)
.build_http();
#[cfg(feature = "dynamic_routing")]
let dynamic_routing_connection = self
.dynamic_routing_client
.clone()
.map(|config| config.get_dynamic_routing_connection(client.clone()))
.transpose()
.expect("Failed to establish a connection with the Dynamic Routing Server")
.flatten();
#[cfg(feature = "dynamic_routing")]
let health_client = HealthCheckClient::build_connections(self, client.clone())
.await
.expect("Failed to build gRPC connections");
let unified_connector_service_client =
UnifiedConnectorServiceClient::build_connections(self).await;
#[cfg(feature = "revenue_recovery")]
let recovery_decider_client = {
match &self.recovery_decider_client {
Some(config) => {
// Validate the config first
config
.validate()
.expect("Recovery Decider configuration validation failed");
// Create the client
let client = config
.get_recovery_decider_connection(client.clone())
.expect(
"Failed to establish a connection with the Recovery Decider Server",
);
logger::info!("Recovery Decider gRPC client successfully initialized");
let boxed_client: Box<dyn RecoveryDeciderClientInterface> = Box::new(client);
Some(boxed_client)
}
None => {
logger::debug!("Recovery Decider client configuration not provided, client will be disabled");
None
}
}
};
Arc::new(GrpcClients {
#[cfg(feature = "dynamic_routing")]
dynamic_routing: dynamic_routing_connection,
#[cfg(feature = "dynamic_routing")]
health_client,
#[cfg(feature = "revenue_recovery")]
recovery_decider_client,
unified_connector_service_client,
})
}
}
/// Contains grpc headers
#[derive(Debug)]
pub struct GrpcHeaders {
/// Tenant id
pub tenant_id: String,
/// Request id
pub request_id: Option<String>,
}
/// Contains grpc headers for Ucs
#[derive(Debug, TypedBuilder)]
pub struct GrpcHeadersUcs {
/// Tenant id
tenant_id: String,
/// Request id
request_id: Option<RequestId>,
/// Lineage ids
lineage_ids: LineageIds,
/// External vault proxy metadata
external_vault_proxy_metadata: Option<String>,
/// Merchant Reference Id
merchant_reference_id: Option<ucs_types::UcsReferenceId>,
shadow_mode: Option<bool>,
}
/// Type aliase for GrpcHeaders builder in initial stage
pub type GrpcHeadersUcsBuilderInitial =
GrpcHeadersUcsBuilder<((String,), (Option<RequestId>,), (), (), (), (Option<bool>,))>;
/// Type aliase for GrpcHeaders builder in intermediate stage
pub type GrpcHeadersUcsBuilderFinal = GrpcHeadersUcsBuilder<(
(String,),
(Option<RequestId>,),
(LineageIds,),
(Option<String>,),
(Option<ucs_types::UcsReferenceId>,),
(Option<bool>,),
)>;
/// struct to represent set of Lineage ids
#[derive(Debug, Clone, serde::Serialize)]
pub struct LineageIds {
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
}
impl LineageIds {
/// constructor for LineageIds
pub fn new(merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId) -> Self {
Self {
merchant_id,
profile_id,
}
}
/// get url encoded string representation of LineageIds
pub fn get_url_encoded_string(self) -> Result<String, serde_urlencoded::ser::Error> {
serde_urlencoded::to_string(&self)
}
}
#[cfg(feature = "dynamic_routing")]
/// Trait to add necessary headers to the tonic Request
pub(crate) trait AddHeaders {
/// Add necessary header fields to the tonic Request
fn add_headers_to_grpc_request(&mut self, headers: GrpcHeaders);
}
#[cfg(feature = "dynamic_routing")]
impl<T> AddHeaders for tonic::Request<T> {
#[track_caller]
fn add_headers_to_grpc_request(&mut self, headers: GrpcHeaders) {
headers.tenant_id
.parse()
.map(|tenant_id| {
self
.metadata_mut()
.append(consts::TENANT_HEADER, tenant_id)
})
.inspect_err(
|err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::TENANT_HEADER),
)
.ok();
headers.request_id.map(|request_id| {
request_id
.parse()
.map(|request_id| {
self
.metadata_mut()
.append(consts::X_REQUEST_ID, request_id)
})
.inspect_err(
|err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::X_REQUEST_ID),
)
.ok();
});
}
}
#[cfg(feature = "dynamic_routing")]
pub(crate) fn create_grpc_request<T: Debug>(message: T, headers: GrpcHeaders) -> tonic::Request<T> {
let mut request = tonic::Request::new(message);
request.add_headers_to_grpc_request(headers);
logger::info!(?request);
request
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/hubspot_proxy.rs | crates/external_services/src/hubspot_proxy.rs | use masking::Secret;
/// Lead source constant for Hubspot
pub const HUBSPOT_LEAD_SOURCE: &str = "Hyperswitch Dashboard";
/// Struct representing a request to Hubspot
#[derive(Clone, Debug, serde::Serialize, Default)]
pub struct HubspotRequest {
/// Indicates whether Hubspot should be used.
#[serde(rename = "useHubspot")]
pub use_hubspot: bool,
/// The country of the user or company.
pub country: String,
/// The ID of the Hubspot form being submitted.
#[serde(rename = "hubspotFormId")]
pub hubspot_form_id: String,
/// The first name of the user.
pub firstname: Secret<String>,
/// The last name of the user.
pub lastname: Secret<String>,
/// The email address of the user.
pub email: Secret<String>,
/// The name of the company.
#[serde(rename = "companyName")]
pub company_name: String,
/// The source of the lead, typically set to "Hyperswitch Dashboard".
pub lead_source: String,
/// The website URL of the company.
pub website: String,
/// The phone number of the user.
pub phone: Secret<String>,
/// The role or designation of the user.
pub role: String,
/// The monthly GMV (Gross Merchandise Value) of the company.
#[serde(rename = "monthlyGMV")]
pub monthly_gmv: String,
/// Notes from the business development team.
pub bd_notes: String,
/// Additional message or comments.
pub message: String,
}
#[allow(missing_docs)]
impl HubspotRequest {
pub fn new(
country: String,
hubspot_form_id: String,
firstname: Secret<String>,
email: Secret<String>,
company_name: String,
website: String,
) -> Self {
Self {
use_hubspot: true,
country,
hubspot_form_id,
firstname,
email,
company_name,
lead_source: HUBSPOT_LEAD_SOURCE.to_string(),
website,
..Default::default()
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/superposition.rs | crates/external_services/src/superposition.rs | //! Superposition client for dynamic configuration management
/// Type definitions for Superposition integration
pub mod types;
use std::collections::HashMap;
use common_utils::errors::CustomResult;
use error_stack::report;
use masking::ExposeInterface;
pub use self::types::{ConfigContext, SuperpositionClientConfig, SuperpositionError};
fn convert_open_feature_value(value: open_feature::Value) -> Result<serde_json::Value, String> {
match value {
open_feature::Value::String(s) => Ok(serde_json::Value::String(s)),
open_feature::Value::Bool(b) => Ok(serde_json::Value::Bool(b)),
open_feature::Value::Int(n) => Ok(serde_json::Value::Number(serde_json::Number::from(n))),
open_feature::Value::Float(f) => serde_json::Number::from_f64(f)
.map(serde_json::Value::Number)
.ok_or_else(|| format!("Invalid number: {f}")),
open_feature::Value::Struct(sv) => Ok(types::JsonValue::try_from(sv)?.into_inner()),
open_feature::Value::Array(values) => Ok(serde_json::Value::Array(
values
.into_iter()
.map(convert_open_feature_value)
.collect::<Result<Vec<_>, _>>()?,
)),
}
}
/// Superposition client wrapper
// Debug trait cannot be derived because open_feature::Client doesn't implement Debug
#[allow(missing_debug_implementations)]
pub struct SuperpositionClient {
client: open_feature::Client,
}
impl SuperpositionClient {
/// Create a new Superposition client
pub async fn new(config: SuperpositionClientConfig) -> CustomResult<Self, SuperpositionError> {
let provider_options = superposition_provider::SuperpositionProviderOptions {
endpoint: config.endpoint.clone(),
token: config.token.expose(),
org_id: config.org_id.clone(),
workspace_id: config.workspace_id.clone(),
fallback_config: None,
evaluation_cache: None,
refresh_strategy: superposition_provider::RefreshStrategy::Polling(
superposition_provider::PollingStrategy {
interval: config.polling_interval,
timeout: config.request_timeout,
},
),
experimentation_options: None,
};
// Create provider and set up OpenFeature
let provider = superposition_provider::SuperpositionProvider::new(provider_options);
// Initialize OpenFeature API and set provider
let mut api = open_feature::OpenFeature::singleton_mut().await;
api.set_provider(provider).await;
// Create client
let client = api.create_client();
router_env::logger::info!("Superposition client initialized successfully");
Ok(Self { client })
}
/// Build evaluation context for Superposition requests
fn build_evaluation_context(
&self,
context: Option<&ConfigContext>,
) -> open_feature::EvaluationContext {
open_feature::EvaluationContext {
custom_fields: context.map_or(HashMap::new(), |ctx| {
ctx.values
.iter()
.map(|(k, v)| {
(
k.clone(),
open_feature::EvaluationContextFieldValue::String(v.clone()),
)
})
.collect()
}),
targeting_key: None,
}
}
/// Get a boolean configuration value from Superposition
pub async fn get_bool_value(
&self,
key: &str,
context: Option<&ConfigContext>,
) -> CustomResult<bool, SuperpositionError> {
let evaluation_context = self.build_evaluation_context(context);
self.client
.get_bool_value(key, Some(&evaluation_context), None)
.await
.map_err(|e| {
report!(SuperpositionError::ClientError(format!(
"Failed to get bool value for key '{key}': {e:?}"
)))
})
}
/// Get a string configuration value from Superposition
pub async fn get_string_value(
&self,
key: &str,
context: Option<&ConfigContext>,
) -> CustomResult<String, SuperpositionError> {
let evaluation_context = self.build_evaluation_context(context);
self.client
.get_string_value(key, Some(&evaluation_context), None)
.await
.map_err(|e| {
report!(SuperpositionError::ClientError(format!(
"Failed to get string value for key '{key}': {e:?}"
)))
})
}
/// Get an integer configuration value from Superposition
pub async fn get_int_value(
&self,
key: &str,
context: Option<&ConfigContext>,
) -> CustomResult<i64, SuperpositionError> {
let evaluation_context = self.build_evaluation_context(context);
self.client
.get_int_value(key, Some(&evaluation_context), None)
.await
.map_err(|e| {
report!(SuperpositionError::ClientError(format!(
"Failed to get int value for key '{key}': {e:?}"
)))
})
}
/// Get a float configuration value from Superposition
pub async fn get_float_value(
&self,
key: &str,
context: Option<&ConfigContext>,
) -> CustomResult<f64, SuperpositionError> {
let evaluation_context = self.build_evaluation_context(context);
self.client
.get_float_value(key, Some(&evaluation_context), None)
.await
.map_err(|e| {
report!(SuperpositionError::ClientError(format!(
"Failed to get float value for key '{key}': {e:?}"
)))
})
}
/// Get an object configuration value from Superposition
pub async fn get_object_value(
&self,
key: &str,
context: Option<&ConfigContext>,
) -> CustomResult<serde_json::Value, SuperpositionError> {
let evaluation_context = self.build_evaluation_context(context);
let json_result = self
.client
.get_struct_value::<types::JsonValue>(key, Some(&evaluation_context), None)
.await
.map_err(|e| {
report!(SuperpositionError::ClientError(format!(
"Failed to get object value for key '{key}': {e:?}"
)))
})?;
Ok(json_result.into_inner())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/utils.rs | crates/external_services/src/utils.rs | //! Custom deserializers for external services configuration
use std::collections::HashSet;
use serde::Deserialize;
/// Parses a comma-separated string into a HashSet of typed values.
///
/// # Arguments
///
/// * `value` - String or string reference containing comma-separated values
///
/// # Returns
///
/// * `Ok(HashSet<T>)` - Successfully parsed HashSet
/// * `Err(String)` - Error message if any value parsing fails
///
/// # Type Parameters
///
/// * `T` - Target type that implements `FromStr`, `Eq`, and `Hash`
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
///
/// let result: Result<HashSet<i32>, String> =
/// deserialize_hashset_inner("1,2,3");
/// assert!(result.is_ok());
///
/// if let Ok(hashset) = result {
/// assert!(hashset.contains(&1));
/// assert!(hashset.contains(&2));
/// assert!(hashset.contains(&3));
/// }
/// ```
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)
}
}
/// Serde deserializer function for converting comma-separated strings into typed HashSets.
///
/// This function is designed to be used with serde's `#[serde(deserialize_with = "deserialize_hashset")]`
/// attribute to customize deserialization of HashSet fields.
///
/// # Arguments
///
/// * `deserializer` - Serde deserializer instance
///
/// # Returns
///
/// * `Ok(HashSet<T>)` - Successfully deserialized HashSet
/// * `Err(D::Error)` - Serde deserialization error
///
/// # Type Parameters
///
/// * `D` - Serde deserializer type
/// * `T` - Target type that implements `FromStr`, `Eq`, and `Hash`
pub(crate) 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)
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
#[test]
fn test_deserialize_hashset_inner_success() {
let result: Result<HashSet<i32>, String> = deserialize_hashset_inner("1,2,3");
assert!(result.is_ok());
if let Ok(hashset) = result {
assert_eq!(hashset.len(), 3);
assert!(hashset.contains(&1));
assert!(hashset.contains(&2));
assert!(hashset.contains(&3));
}
}
#[test]
fn test_deserialize_hashset_inner_with_whitespace() {
let result: Result<HashSet<String>, String> = deserialize_hashset_inner(" a , b , c ");
assert!(result.is_ok());
if let Ok(hashset) = result {
assert_eq!(hashset.len(), 3);
assert!(hashset.contains("a"));
assert!(hashset.contains("b"));
assert!(hashset.contains("c"));
}
}
#[test]
fn test_deserialize_hashset_inner_empty_string() {
let result: Result<HashSet<String>, String> = deserialize_hashset_inner("");
assert!(result.is_ok());
if let Ok(hashset) = result {
assert_eq!(hashset.len(), 0);
}
}
#[test]
fn test_deserialize_hashset_inner_single_value() {
let result: Result<HashSet<String>, String> = deserialize_hashset_inner("single");
assert!(result.is_ok());
if let Ok(hashset) = result {
assert_eq!(hashset.len(), 1);
assert!(hashset.contains("single"));
}
}
#[test]
fn test_deserialize_hashset_inner_invalid_int() {
let result: Result<HashSet<i32>, String> = deserialize_hashset_inner("1,invalid,3");
assert!(result.is_err());
if let Err(error) = result {
assert!(error.contains("Unable to deserialize `invalid` as `i32`"));
}
}
#[test]
fn test_deserialize_hashset_inner_duplicates() {
let result: Result<HashSet<String>, String> = deserialize_hashset_inner("a,b,a,c,b");
assert!(result.is_ok());
if let Ok(hashset) = result {
assert_eq!(hashset.len(), 3); // Duplicates should be removed
assert!(hashset.contains("a"));
assert!(hashset.contains("b"));
assert!(hashset.contains("c"));
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/file_storage.rs | crates/external_services/src/file_storage.rs | //! Module for managing file storage operations with support for multiple storage schemes.
use std::{
fmt::{Display, Formatter},
sync::Arc,
};
use common_utils::errors::CustomResult;
/// Includes functionality for AWS S3 storage operations.
#[cfg(feature = "aws_s3")]
mod aws_s3;
mod file_system;
/// Enum representing different file storage configurations, allowing for multiple storage schemes.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "file_storage_backend")]
#[serde(rename_all = "snake_case")]
pub enum FileStorageConfig {
/// AWS S3 storage configuration.
#[cfg(feature = "aws_s3")]
AwsS3 {
/// Configuration for AWS S3 file storage.
aws_s3: aws_s3::AwsFileStorageConfig,
},
/// Local file system storage configuration.
#[default]
FileSystem,
}
impl FileStorageConfig {
/// Validates the file storage configuration.
pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
match self {
#[cfg(feature = "aws_s3")]
Self::AwsS3 { aws_s3 } => aws_s3.validate(),
Self::FileSystem => Ok(()),
}
}
/// Retrieves the appropriate file storage client based on the file storage configuration.
pub async fn get_file_storage_client(&self) -> Arc<dyn FileStorageInterface> {
match self {
#[cfg(feature = "aws_s3")]
Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await),
Self::FileSystem => Arc::new(file_system::FileSystem),
}
}
}
/// Trait for file storage operations
#[async_trait::async_trait]
pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send {
/// Uploads a file to the selected storage scheme.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError>;
/// Deletes a file from the selected storage scheme.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError>;
/// Retrieves a file from the selected storage scheme.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>;
}
dyn_clone::clone_trait_object!(FileStorageInterface);
/// Error thrown when the file storage config is invalid
#[derive(Debug, Clone)]
pub struct InvalidFileStorageConfig(&'static str);
impl std::error::Error for InvalidFileStorageConfig {}
impl Display for InvalidFileStorageConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "file_storage: {}", self.0)
}
}
/// Represents errors that can occur during file storage operations.
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum FileStorageError {
/// Indicates that the file upload operation failed.
#[error("Failed to upload file")]
UploadFailed,
/// Indicates that the file retrieval operation failed.
#[error("Failed to retrieve file")]
RetrieveFailed,
/// Indicates that the file deletion operation failed.
#[error("Failed to delete file")]
DeleteFailed,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/managers.rs | crates/external_services/src/managers.rs | //! Config and client managers
pub mod encryption_management;
pub mod secrets_management;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/aws_kms.rs | crates/external_services/src/aws_kms.rs | //! Interactions with the AWS KMS SDK
pub mod core;
pub mod implementers;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/crm.rs | crates/external_services/src/crm.rs | use std::sync::Arc;
use common_utils::{
errors::CustomResult,
ext_traits::ConfigExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use http::header;
use hyperswitch_interfaces::{
crm::{CrmInterface, CrmPayload},
errors::HttpClientError,
types::Proxy,
};
use router_env::logger;
use crate::{http_client, hubspot_proxy::HubspotRequest};
/// Hubspot Crm configuration
#[derive(Debug, Clone, serde::Deserialize)]
pub struct HubspotProxyConfig {
/// The ID of the Hubspot form to be submitted.
pub form_id: String,
/// The URL to which the Hubspot form data will be sent.
pub request_url: String,
}
impl HubspotProxyConfig {
/// Validates Hubspot configuration
pub(super) fn validate(&self) -> Result<(), InvalidCrmConfig> {
use common_utils::fp_utils::when;
when(self.request_url.is_default_or_empty(), || {
Err(InvalidCrmConfig("request url must not be empty"))
})?;
when(self.form_id.is_default_or_empty(), || {
Err(InvalidCrmConfig("form_id must not be empty"))
})
}
}
/// Error thrown when the crm config is invalid
#[derive(Debug, Clone)]
pub struct InvalidCrmConfig(pub &'static str);
impl std::error::Error for InvalidCrmConfig {}
impl std::fmt::Display for InvalidCrmConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "crm: {}", self.0)
}
}
#[derive(Debug, Clone, Copy)]
/// NoCrm struct
pub struct NoCrm;
/// Enum representing different Crm configurations
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "crm_manager")]
#[serde(rename_all = "snake_case")]
pub enum CrmManagerConfig {
/// Hubspot Crm configuration
HubspotProxy {
/// Hubspot Crm configuration
hubspot_proxy: HubspotProxyConfig,
},
/// No Crm configuration
#[default]
NoCrm,
}
impl CrmManagerConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), InvalidCrmConfig> {
match self {
Self::HubspotProxy { hubspot_proxy } => hubspot_proxy.validate(),
Self::NoCrm => Ok(()),
}
}
/// Retrieves the appropriate Crm client based on the configuration.
pub async fn get_crm_client(&self) -> Arc<dyn CrmInterface> {
match self {
Self::HubspotProxy { hubspot_proxy } => Arc::new(hubspot_proxy.clone()),
Self::NoCrm => Arc::new(NoCrm),
}
}
}
#[async_trait::async_trait]
impl CrmInterface for NoCrm {
async fn make_body(&self, _details: CrmPayload) -> RequestContent {
RequestContent::Json(Box::new(()))
}
async fn make_request(&self, _body: RequestContent, _origin_base_url: String) -> Request {
RequestBuilder::default().build()
}
async fn send_request(
&self,
_proxy: &Proxy,
_request: Request,
) -> CustomResult<reqwest::Response, HttpClientError> {
logger::info!("No CRM configured!");
Err(HttpClientError::UnexpectedState).attach_printable("No CRM configured!")
}
}
#[async_trait::async_trait]
impl CrmInterface for HubspotProxyConfig {
async fn make_body(&self, details: CrmPayload) -> RequestContent {
RequestContent::FormUrlEncoded(Box::new(HubspotRequest::new(
details.business_country_name.unwrap_or_default(),
self.form_id.clone(),
details.poc_name.unwrap_or_default(),
details.poc_email.clone().unwrap_or_default(),
details.legal_business_name.unwrap_or_default(),
details.business_website.unwrap_or_default(),
)))
}
async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request {
RequestBuilder::new()
.method(Method::Post)
.url(self.request_url.as_str())
.set_body(body)
.attach_default_headers()
.headers(vec![(
header::ORIGIN.to_string(),
format!("{origin_base_url}/dashboard").into(),
)])
.build()
}
async fn send_request(
&self,
proxy: &Proxy,
request: Request,
) -> CustomResult<reqwest::Response, HttpClientError> {
http_client::send_request(proxy, request, None).await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/hashicorp_vault.rs | crates/external_services/src/hashicorp_vault.rs | //! Interactions with the HashiCorp Vault
pub mod core;
pub mod implementers;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/superposition/types.rs | crates/external_services/src/superposition/types.rs | //! Type definitions for Superposition integration
use std::collections::HashMap;
use common_utils::{errors::CustomResult, fp_utils::when};
use masking::{ExposeInterface, Secret};
/// Wrapper type for JSON values from Superposition
#[derive(Debug, Clone)]
pub struct JsonValue(serde_json::Value);
impl JsonValue {
/// Consume the wrapper and return the inner JSON value
pub(super) fn into_inner(self) -> serde_json::Value {
self.0
}
}
impl TryFrom<open_feature::StructValue> for JsonValue {
type Error = String;
fn try_from(sv: open_feature::StructValue) -> Result<Self, Self::Error> {
let capacity = sv.fields.len();
sv.fields
.into_iter()
.try_fold(
serde_json::Map::with_capacity(capacity),
|mut map, (k, v)| {
let value = super::convert_open_feature_value(v)?;
map.insert(k, value);
Ok(map)
},
)
.map(|map| Self(serde_json::Value::Object(map)))
}
}
/// Configuration for Superposition integration
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(default)]
pub struct SuperpositionClientConfig {
/// Whether Superposition is enabled
pub enabled: bool,
/// Superposition API endpoint
pub endpoint: String,
/// Authentication token for Superposition
pub token: Secret<String>,
/// Organization ID in Superposition
pub org_id: String,
/// Workspace ID in Superposition
pub workspace_id: String,
/// Polling interval in seconds for configuration updates
pub polling_interval: u64,
/// Request timeout in seconds for Superposition API calls (None = no timeout)
pub request_timeout: Option<u64>,
}
impl Default for SuperpositionClientConfig {
fn default() -> Self {
Self {
enabled: false,
endpoint: String::new(),
token: Secret::new(String::new()),
org_id: String::new(),
workspace_id: String::new(),
polling_interval: 15,
request_timeout: None,
}
}
}
/// Errors that can occur when using Superposition
#[derive(Debug, thiserror::Error)]
pub enum SuperpositionError {
/// Error initializing the Superposition client
#[error("Failed to initialize Superposition client: {0}")]
ClientInitError(String),
/// Error from the Superposition client
#[error("Superposition client error: {0}")]
ClientError(String),
/// Invalid configuration provided
#[error("Invalid configuration: {0}")]
InvalidConfiguration(String),
}
/// Context for configuration requests
#[derive(Debug, Clone, Default)]
pub struct ConfigContext {
/// Key-value pairs for configuration context
pub(super) values: HashMap<String, String>,
}
impl SuperpositionClientConfig {
/// Validate the Superposition configuration
pub fn validate(&self) -> Result<(), SuperpositionError> {
if !self.enabled {
return Ok(());
}
when(self.endpoint.is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition endpoint cannot be empty".to_string(),
))
})?;
when(url::Url::parse(&self.endpoint).is_err(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition endpoint must be a valid URL".to_string(),
))
})?;
when(self.token.clone().expose().is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition token cannot be empty".to_string(),
))
})?;
when(self.org_id.is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition org_id cannot be empty".to_string(),
))
})?;
when(self.workspace_id.is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition workspace_id cannot be empty".to_string(),
))
})?;
Ok(())
}
}
impl ConfigContext {
/// Create a new empty context
pub fn new() -> Self {
Self::default()
}
/// Add a key-value pair to the context. Replaces existing value if key exists.
pub fn with(mut self, key: &str, value: &str) -> Self {
self.values.insert(key.to_string(), value.to_string());
self
}
}
#[cfg(feature = "superposition")]
#[async_trait::async_trait]
impl hyperswitch_interfaces::secrets_interface::secret_handler::SecretsHandler
for SuperpositionClientConfig
{
async fn convert_to_raw_secret(
value: hyperswitch_interfaces::secrets_interface::secret_state::SecretStateContainer<
Self,
hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret,
>,
secret_management_client: &dyn hyperswitch_interfaces::secrets_interface::SecretManagementInterface,
) -> CustomResult<
hyperswitch_interfaces::secrets_interface::secret_state::SecretStateContainer<
Self,
hyperswitch_interfaces::secrets_interface::secret_state::RawSecret,
>,
hyperswitch_interfaces::secrets_interface::SecretsManagementError,
> {
let superposition_config = value.get_inner();
let token = if superposition_config.enabled {
secret_management_client
.get_secret(superposition_config.token.clone())
.await?
} else {
superposition_config.token.clone()
};
Ok(value.transition_state(|superposition_config| Self {
token,
..superposition_config
}))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/managers/secrets_management.rs | crates/external_services/src/managers/secrets_management.rs | //! Secrets management util module
use common_utils::errors::CustomResult;
#[cfg(feature = "hashicorp-vault")]
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::{
SecretManagementInterface, SecretsManagementError,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
#[cfg(feature = "hashicorp-vault")]
use crate::hashicorp_vault;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for secrets management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "secrets_manager")]
#[serde(rename_all = "snake_case")]
pub enum SecretsManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// HashiCorp-Vault configuration
#[cfg(feature = "hashicorp-vault")]
HashiCorpVault {
/// HC-Vault config
hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl SecretsManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => hc_vault.validate(),
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate secret management client based on the configuration.
pub async fn get_secret_management_client(
&self,
) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => {
Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await))
}
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => {
hashicorp_vault::core::HashiCorpVault::new(hc_vault)
.change_context(SecretsManagementError::ClientCreationFailed)
.map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })
}
Self::NoEncryption => Ok(Box::new(NoEncryption)),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/managers/encryption_management.rs | crates/external_services/src/managers/encryption_management.rs | //! Encryption management util module
use std::sync::Arc;
use common_utils::errors::CustomResult;
use hyperswitch_interfaces::encryption_interface::{
EncryptionError, EncryptionManagementInterface,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for encryption management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "encryption_manager")]
#[serde(rename_all = "snake_case")]
pub enum EncryptionManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl EncryptionManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => {
use common_utils::fp_utils::when;
aws_kms.validate()?;
when(aws_kms.key_id.is_none(), || {
Err("KMS AWS key ID must not be empty")
})
}
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate encryption client based on the configuration.
pub async fn get_encryption_management_client(
&self,
) -> CustomResult<Arc<dyn EncryptionManagementInterface>, EncryptionError> {
Ok(match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
Self::NoEncryption => Arc::new(NoEncryption),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/dynamic_routing.rs | crates/external_services/src/grpc_client/dynamic_routing.rs | /// Module for Contract based routing
pub mod contract_routing_client;
use std::fmt::Debug;
use common_utils::errors::CustomResult;
use router_env::logger;
/// Elimination Routing Client Interface Implementation
pub mod elimination_based_client;
/// Success Routing Client Interface Implementation
pub mod success_rate_client;
pub use contract_routing_client::ContractScoreCalculatorClient;
pub use elimination_based_client::EliminationAnalyserClient;
pub use success_rate_client::SuccessRateCalculatorClient;
use super::Client;
/// Result type for Dynamic Routing
pub type DynamicRoutingResult<T> = CustomResult<T, DynamicRoutingError>;
/// Dynamic Routing Errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum DynamicRoutingError {
/// The required input is missing
#[error("Missing Required Field : {field} for building the Dynamic Routing Request")]
MissingRequiredField {
/// The required field name
field: String,
},
/// Error from Dynamic Routing Server while performing success_rate analysis
#[error("Error from Dynamic Routing Server while perfrming success_rate analysis : {0}")]
SuccessRateBasedRoutingFailure(String),
/// Generic Error from Dynamic Routing Server while performing contract based routing
#[error("Error from Dynamic Routing Server while performing contract based routing: {0}")]
ContractBasedRoutingFailure(String),
/// Generic Error from Dynamic Routing Server while performing contract based routing
#[error("Contract not found in the dynamic routing service")]
ContractNotFound,
/// Error from Dynamic Routing Server while perfrming elimination
#[error("Error from Dynamic Routing Server while perfrming elimination : {0}")]
EliminationRateRoutingFailure(String),
}
/// Type that consists of all the services provided by the client
#[derive(Debug, Clone)]
pub struct RoutingStrategy {
/// success rate service for Dynamic Routing
pub success_rate_client: SuccessRateCalculatorClient<Client>,
/// contract based routing service for Dynamic Routing
pub contract_based_client: ContractScoreCalculatorClient<Client>,
/// elimination service for Dynamic Routing
pub elimination_based_client: EliminationAnalyserClient<Client>,
}
/// Contains the Dynamic Routing Client Config
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
#[serde(untagged)]
pub enum DynamicRoutingClientConfig {
/// If the dynamic routing client config has been enabled
Enabled {
/// The host for the client
host: String,
/// The port of the client
port: u16,
/// Service name
service: String,
},
#[default]
/// If the dynamic routing client config has been disabled
Disabled,
}
impl DynamicRoutingClientConfig {
/// establish connection with the server
pub fn get_dynamic_routing_connection(
self,
client: Client,
) -> Result<Option<RoutingStrategy>, Box<dyn std::error::Error>> {
match self {
Self::Enabled { host, port, .. } => {
let uri = format!("http://{host}:{port}").parse::<tonic::transport::Uri>()?;
logger::info!("Connection established with dynamic routing gRPC Server");
let (success_rate_client, contract_based_client, elimination_based_client) = (
SuccessRateCalculatorClient::with_origin(client.clone(), uri.clone()),
ContractScoreCalculatorClient::with_origin(client.clone(), uri.clone()),
EliminationAnalyserClient::with_origin(client, uri),
);
Ok(Some(RoutingStrategy {
success_rate_client,
contract_based_client,
elimination_based_client,
}))
}
Self::Disabled => Ok(None),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/revenue_recovery.rs | crates/external_services/src/grpc_client/revenue_recovery.rs | /// Recovery Decider client
pub mod recovery_decider_client;
use std::fmt::Debug;
use common_utils::consts;
use router_env::logger;
/// Contains recovery grpc headers
#[derive(Debug)]
pub struct GrpcRecoveryHeaders {
/// Request id
pub request_id: Option<String>,
}
/// Trait to add necessary recovery headers to the tonic Request
pub(crate) trait AddRecoveryHeaders {
/// Add necessary recovery header fields to the tonic Request
fn add_recovery_headers(&mut self, headers: GrpcRecoveryHeaders);
}
impl<T> AddRecoveryHeaders for tonic::Request<T> {
#[track_caller]
fn add_recovery_headers(&mut self, headers: GrpcRecoveryHeaders) {
headers.request_id.map(|request_id| {
request_id
.parse()
.map(|request_id_val| {
self
.metadata_mut()
.append(consts::X_REQUEST_ID, request_id_val)
})
.inspect_err(
|err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::X_REQUEST_ID),
)
.ok();
});
}
}
/// Creates a tonic::Request with recovery headers added.
pub(crate) fn create_revenue_recovery_grpc_request<T: Debug>(
message: T,
recovery_headers: GrpcRecoveryHeaders,
) -> tonic::Request<T> {
let mut request = tonic::Request::new(message);
request.add_recovery_headers(recovery_headers);
request
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/health_check_client.rs | crates/external_services/src/grpc_client/health_check_client.rs | use std::{collections::HashMap, fmt::Debug};
use api_models::health_check::{HealthCheckMap, HealthCheckServices};
use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
use error_stack::ResultExt;
pub use health_check::{
health_check_response::ServingStatus, health_client::HealthClient, HealthCheckRequest,
HealthCheckResponse,
};
use router_env::logger;
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod health_check {
tonic::include_proto!("grpc.health.v1");
}
use super::{Client, DynamicRoutingClientConfig, GrpcClientSettings};
/// Result type for Dynamic Routing
pub type HealthCheckResult<T> = CustomResult<T, HealthCheckError>;
/// Dynamic Routing Errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckError {
/// The required input is missing
#[error("Missing fields: {0} for building the Health check connection")]
MissingFields(String),
/// Error from gRPC Server
#[error("Error from gRPC Server : {0}")]
ConnectionError(String),
/// status is invalid
#[error("Invalid Status from server")]
InvalidStatus,
}
/// Health Check Client type
#[derive(Debug, Clone)]
pub struct HealthCheckClient {
/// Health clients for all gRPC based services
pub clients: HashMap<HealthCheckServices, HealthClient<Client>>,
}
impl HealthCheckClient {
/// Build connections to all gRPC services
pub async fn build_connections(
config: &GrpcClientSettings,
client: Client,
) -> Result<Self, Box<dyn std::error::Error>> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let mut client_map = HashMap::new();
if let Some(conn) = connection {
let uri = format!("http://{}:{}", conn.0, conn.1).parse::<tonic::transport::Uri>()?;
let health_client = HealthClient::with_origin(client, uri);
client_map.insert(HealthCheckServices::DynamicRoutingService, health_client);
}
Ok(Self {
clients: client_map,
})
}
/// Perform health check for all services involved
pub async fn perform_health_check(
&self,
config: &GrpcClientSettings,
) -> HealthCheckResult<HealthCheckMap> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let health_client = self
.clients
.get(&HealthCheckServices::DynamicRoutingService);
// SAFETY : This is a safe cast as there exists a valid
// integer value for this variant
#[allow(clippy::as_conversions)]
let expected_status = ServingStatus::Serving as i32;
let mut service_map = HealthCheckMap::new();
let health_check_succeed = connection
.as_ref()
.async_map(|conn| self.get_response_from_grpc_service(conn.2.clone(), health_client))
.await
.transpose()
.change_context(HealthCheckError::ConnectionError(
"error calling dynamic routing service".to_string(),
))
.map_err(|err| logger::error!(error=?err))
.ok()
.flatten()
.is_some_and(|resp| resp.status == expected_status);
connection.and_then(|_conn| {
service_map.insert(
HealthCheckServices::DynamicRoutingService,
health_check_succeed,
)
});
Ok(service_map)
}
async fn get_response_from_grpc_service(
&self,
service: String,
client: Option<&HealthClient<Client>>,
) -> HealthCheckResult<HealthCheckResponse> {
let request = tonic::Request::new(HealthCheckRequest { service });
let mut client = client
.ok_or(HealthCheckError::MissingFields(
"[health_client]".to_string(),
))?
.clone();
let response = client
.check(request)
.await
.change_context(HealthCheckError::ConnectionError(
"Failed to call dynamic routing service".to_string(),
))?
.into_inner();
Ok(response)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/unified_connector_service.rs | crates/external_services/src/grpc_client/unified_connector_service.rs | use std::collections::{HashMap, HashSet};
use common_enums::connector_enums::Connector;
use common_utils::{consts as common_utils_consts, errors::CustomResult, types::Url};
use error_stack::ResultExt;
pub use hyperswitch_interfaces::unified_connector_service::transformers::UnifiedConnectorServiceError;
use masking::{PeekInterface, Secret};
use router_env::logger;
use tokio::time::{timeout, Duration};
use tonic::{
metadata::{MetadataMap, MetadataValue},
transport::Uri,
};
use unified_connector_service_client::payments::{
self as payments_grpc, payment_service_client::PaymentServiceClient,
refund_service_client::RefundServiceClient, PaymentServiceAuthorizeResponse,
PaymentServiceRefundRequest, PaymentServiceTransformRequest, PaymentServiceTransformResponse,
RefundResponse, RefundServiceGetRequest,
};
use crate::{
consts,
grpc_client::{GrpcClientSettings, GrpcHeadersUcs},
utils::deserialize_hashset,
};
/// Result type for Dynamic Routing
pub type UnifiedConnectorServiceResult<T> = CustomResult<T, UnifiedConnectorServiceError>;
/// Contains the Unified Connector Service client
#[derive(Debug, Clone)]
pub struct UnifiedConnectorServiceClient {
/// The Unified Connector Service Client
pub client: PaymentServiceClient<tonic::transport::Channel>,
/// The Refund Service Client
pub refund_client: RefundServiceClient<tonic::transport::Channel>,
}
/// Contains the Unified Connector Service Client config
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct UnifiedConnectorServiceClientConfig {
/// Base URL of the gRPC Server
pub base_url: Url,
/// Contains the connection timeout duration in seconds
pub connection_timeout: u64,
/// Set of external services/connectors available for the unified connector service
#[serde(default, deserialize_with = "deserialize_hashset")]
pub ucs_only_connectors: HashSet<Connector>,
/// Set of connectors for which psync is disabled in unified connector service
#[serde(default, deserialize_with = "deserialize_hashset")]
pub ucs_psync_disabled_connectors: HashSet<Connector>,
}
/// Contains the Connector Auth Type and related authentication data.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ConnectorAuthMetadata {
/// Name of the connector (e.g., "stripe", "paypal").
pub connector_name: String,
/// Type of authentication used (e.g., "HeaderKey", "BodyKey", "SignatureKey").
pub auth_type: String,
/// Optional API key used for authentication.
pub api_key: Option<Secret<String>>,
/// Optional additional key used by some authentication types.
pub key1: Option<Secret<String>>,
/// Optional second additional key used by multi-auth authentication types.
pub key2: Option<Secret<String>>,
/// Optional API secret used for signature or secure authentication.
pub api_secret: Option<Secret<String>>,
/// Optional auth_key_map used for authentication.
pub auth_key_map:
Option<HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>>,
/// Id of the merchant.
pub merchant_id: Secret<String>,
}
/// External Vault Proxy Related Metadata
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ExternalVaultProxyMetadata {
/// VGS proxy data variant
VgsMetadata(VgsMetadata),
}
/// VGS proxy data
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct VgsMetadata {
/// External vault url
pub proxy_url: Url,
/// CA certificates to verify the vault server
pub certificate: Secret<String>,
}
impl UnifiedConnectorServiceClient {
/// Builds the connection to the gRPC service
pub async fn build_connections(config: &GrpcClientSettings) -> Option<Self> {
match &config.unified_connector_service {
Some(unified_connector_service_client_config) => {
let uri: Uri = match unified_connector_service_client_config
.base_url
.get_string_repr()
.parse()
{
Ok(parsed_uri) => parsed_uri,
Err(err) => {
logger::error!(error = ?err, "Failed to parse URI for Unified Connector Service");
return None;
}
};
let payment_client_result = timeout(
Duration::from_secs(unified_connector_service_client_config.connection_timeout),
PaymentServiceClient::connect(uri.clone()),
)
.await;
let refund_client_result = timeout(
Duration::from_secs(unified_connector_service_client_config.connection_timeout),
RefundServiceClient::connect(uri),
)
.await;
match (payment_client_result, refund_client_result) {
(Ok(Ok(client)), Ok(Ok(refund_client))) => {
logger::info!("Successfully connected to Unified Connector Service");
Some(Self {
client,
refund_client,
})
}
(Ok(Err(err)), _) | (_, Ok(Err(err))) => {
logger::error!(error = ?err, "Failed to connect to Unified Connector Service");
None
}
(Err(err), _) | (_, Err(err)) => {
logger::error!(error = ?err, "Connection to Unified Connector Service timed out");
None
}
}
}
None => {
router_env::logger::error!(?config.unified_connector_service, "Unified Connector Service config is missing");
None
}
}
}
/// Performs Payment Method Token Create
pub async fn payment_method_token_create(
&self,
pm_token_create_request: payments_grpc::PaymentServiceCreatePaymentMethodTokenRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceCreatePaymentMethodTokenResponse>,
> {
let mut request = tonic::Request::new(pm_token_create_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.create_payment_method_token(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentMethodTokenCreateFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="create_payment_method_token",
connector_name=?connector_name,
"UCS create_payment_method_token gRPC call failed"
)
})
}
/// Performs SDK Session Token Create
pub async fn sdk_session_token(
&self,
sdk_session_token_request: payments_grpc::PaymentServiceSdkSessionTokenRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceSdkSessionTokenResponse>,
> {
let mut request = tonic::Request::new(sdk_session_token_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.sdk_session_token(request)
.await
.change_context(UnifiedConnectorServiceError::SdkSessionTokenFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="sdk_session_token",
connector_name=?connector_name,
"UCS sdk_session_token gRPC call failed"
)
})
}
/// Performs Payment Granular Authorize
pub async fn payment_authorize_granular(
&self,
payment_authorize_only_request: payments_grpc::PaymentServiceAuthorizeOnlyRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceAuthorizeResponse>> {
let mut request = tonic::Request::new(payment_authorize_only_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.authorize_only(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentAuthorizeGranularFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="authorize_only",
connector_name=?connector_name,
"UCS authorize_only gRPC call failed"
)
})
}
/// Performs Create Connector Customer Granular
pub async fn create_connector_customer(
&self,
create_customer_request: payments_grpc::PaymentServiceCreateConnectorCustomerRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceCreateConnectorCustomerResponse>,
> {
let mut request = tonic::Request::new(create_customer_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.create_connector_customer(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentConnectorCustomerCreateFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="create_connector_customer_granular",
connector_name=?connector_name,
"UCS create connector customer granular gRPC call failed"
)
})
}
/// Performs Payment Create Order
pub async fn payment_create_order(
&self,
payment_create_order_request: payments_grpc::PaymentServiceCreateOrderRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceCreateOrderResponse>,
> {
let mut request = tonic::Request::new(payment_create_order_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.create_order(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentCreateOrderFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="create_order",
connector_name=?connector_name,
"UCS create_order gRPC call failed"
)
})
}
/// Performs Payment Pre Authenticate
pub async fn payment_pre_authenticate(
&self,
payment_pre_authenticate_request: payments_grpc::PaymentServicePreAuthenticateRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServicePreAuthenticateResponse>,
> {
let mut request = tonic::Request::new(payment_pre_authenticate_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.pre_authenticate(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentPreAuthenticateFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_pre_authenticate",
connector_name=?connector_name,
"UCS payment pre authenticate gRPC call failed"
)
})
}
/// Performs Payment Authenticate
pub async fn payment_authenticate(
&self,
payment_authenticate_request: payments_grpc::PaymentServiceAuthenticateRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceAuthenticateResponse>,
> {
let mut request = tonic::Request::new(payment_authenticate_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.authenticate(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentAuthenticateFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_pre_authenticate",
connector_name=?connector_name,
"UCS payment pre authenticate gRPC call failed"
)
})
}
/// Performs Payment Session token create
pub async fn payment_session_token_create(
&self,
payment_create_session_token_request: payments_grpc::PaymentServiceCreateSessionTokenRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceCreateSessionTokenResponse>,
> {
let mut request = tonic::Request::new(payment_create_session_token_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.create_session_token(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentCreateSessionTokenFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="create_session_token",
connector_name=?connector_name,
"UCS payment create_session_token gRPC call failed"
)
})
}
/// Performs Payment Post Authenticate
pub async fn payment_post_authenticate(
&self,
payment_post_authenticate_request: payments_grpc::PaymentServicePostAuthenticateRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServicePostAuthenticateResponse>,
> {
let mut request = tonic::Request::new(payment_post_authenticate_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.post_authenticate(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentPostAuthenticateFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_post_authenticate",
connector_name=?connector_name,
"UCS payment post authenticate gRPC call failed"
)
})
}
/// Performs Payment Authorize
pub async fn payment_authorize(
&self,
payment_authorize_request: payments_grpc::PaymentServiceAuthorizeRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceAuthorizeResponse>> {
let mut request = tonic::Request::new(payment_authorize_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.authorize(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentAuthorizeFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_authorize",
connector_name=?connector_name,
"UCS payment authorize gRPC call failed"
)
})
}
/// Performs Payment Sync/Get
pub async fn payment_get(
&self,
payment_get_request: payments_grpc::PaymentServiceGetRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceGetResponse>>
{
let mut request = tonic::Request::new(payment_get_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.get(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentGetFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_get",
connector_name=?connector_name,
"UCS payment get/sync gRPC call failed"
)
})
}
/// Performs Payment Capture
pub async fn payment_capture(
&self,
payment_capture_request: payments_grpc::PaymentServiceCaptureRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceCaptureResponse>>
{
let mut request = tonic::Request::new(payment_capture_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.capture(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentCaptureFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_capture",
connector_name=?connector_name,
"UCS payment capture gRPC call failed"
)
})
}
/// Performs Payment Setup Mandate
pub async fn payment_setup_mandate(
&self,
payment_register_request: payments_grpc::PaymentServiceRegisterRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceRegisterResponse>>
{
let mut request = tonic::Request::new(payment_register_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.register(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRegisterFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_setup_mandate",
connector_name=?connector_name,
"UCS payment setup mandate gRPC call failed"
)
})
}
/// Performs Payment Setup Mandate
pub async fn payment_setup_mandate_granular(
&self,
payment_register_request: payments_grpc::PaymentServiceRegisterRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceRegisterResponse>>
{
let mut request = tonic::Request::new(payment_register_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.register_only(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRegisterFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_setup_mandate_granular",
connector_name=?connector_name,
"UCS payment granular setup mandate gRPC call failed"
)
})
}
/// Performs Payment repeat (MIT - Merchant Initiated Transaction).
pub async fn payment_repeat(
&self,
payment_repeat_request: payments_grpc::PaymentServiceRepeatEverythingRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceRepeatEverythingResponse>,
> {
let mut request = tonic::Request::new(payment_repeat_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.repeat_everything(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRepeatEverythingFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_repeat",
connector_name=?connector_name,
"UCS payment repeat gRPC call failed"
)
})
}
/// Performs Payment Cancel/Void
pub async fn payment_cancel(
&self,
payment_void_request: payments_grpc::PaymentServiceVoidRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceVoidResponse>>
{
let mut request = tonic::Request::new(payment_void_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.void(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentCancelFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_cancel",
connector_name=?connector_name,
"UCS payment cancel gRPC call failed"
)
})
}
/// Transforms incoming webhook through UCS
pub async fn transform_incoming_webhook(
&self,
webhook_transform_request: PaymentServiceTransformRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceTransformResponse>> {
let mut request = tonic::Request::new(webhook_transform_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.transform(request)
.await
.change_context(UnifiedConnectorServiceError::WebhookTransformFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="transform_incoming_webhook",
connector_name=?connector_name,
"UCS webhook transform gRPC call failed"
)
})
}
/// Performs Payment Refund through PaymentService.Refund
pub async fn payment_refund(
&self,
payment_refund_request: PaymentServiceRefundRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<RefundResponse>> {
let mut request = tonic::Request::new(payment_refund_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.refund(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRefundFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_refund",
connector_name=?connector_name,
"UCS payment refund gRPC call failed"
)
})
}
/// Performs Refund Sync through RefundService.Get
pub async fn refund_sync(
&self,
refund_sync_request: RefundServiceGetRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<RefundResponse>> {
let mut request = tonic::Request::new(refund_sync_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.refund_client
.clone()
.get(request)
.await
.change_context(UnifiedConnectorServiceError::RefundSyncFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="refund_sync",
connector_name=?connector_name,
"UCS refund sync gRPC call failed"
)
})
}
/// Performs Create Access Token Granular
pub async fn create_access_token(
&self,
create_access_token_request: payments_grpc::PaymentServiceCreateAccessTokenRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceCreateAccessTokenResponse>,
> {
let mut request = tonic::Request::new(create_access_token_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.create_access_token(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentCreateAccessTokenFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="create_access_token",
connector_name=?connector_name,
"UCS create access token granular gRPC call failed"
)
})
}
}
/// Build the gRPC Headers for Unified Connector Service Request
pub fn build_unified_connector_service_grpc_headers(
meta: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> Result<MetadataMap, UnifiedConnectorServiceError> {
let mut metadata = MetadataMap::new();
let parse =
|key: &str, value: &str| -> Result<MetadataValue<_>, UnifiedConnectorServiceError> {
value.parse::<MetadataValue<_>>().map_err(|error| {
logger::error!(?error);
UnifiedConnectorServiceError::HeaderInjectionFailed(key.to_string())
})
};
metadata.append(
consts::UCS_HEADER_CONNECTOR,
parse("connector", &meta.connector_name)?,
);
metadata.append(
consts::UCS_HEADER_AUTH_TYPE,
parse("auth_type", &meta.auth_type)?,
);
if let Some(api_key) = meta.api_key {
metadata.append(
consts::UCS_HEADER_API_KEY,
parse("api_key", api_key.peek())?,
);
}
if let Some(key1) = meta.key1 {
metadata.append(consts::UCS_HEADER_KEY1, parse("key1", key1.peek())?);
}
if let Some(key2) = meta.key2 {
metadata.append(consts::UCS_HEADER_KEY2, parse("key2", key2.peek())?);
}
if let Some(api_secret) = meta.api_secret {
metadata.append(
consts::UCS_HEADER_API_SECRET,
parse("api_secret", api_secret.peek())?,
);
}
if let Some(auth_key_map) = meta.auth_key_map {
let auth_key_map_str = serde_json::to_string(&auth_key_map).map_err(|error| {
logger::error!(?error);
UnifiedConnectorServiceError::ParsingFailed
})?;
metadata.append(
consts::UCS_HEADER_AUTH_KEY_MAP,
parse("auth_key_map", &auth_key_map_str)?,
);
}
metadata.append(
common_utils_consts::X_MERCHANT_ID,
parse(common_utils_consts::X_MERCHANT_ID, meta.merchant_id.peek())?,
);
if let Some(external_vault_proxy_metadata) = grpc_headers.external_vault_proxy_metadata {
metadata.append(
consts::UCS_HEADER_EXTERNAL_VAULT_METADATA,
parse("external_vault_metadata", &external_vault_proxy_metadata)?,
);
};
let lineage_ids_str = grpc_headers
.lineage_ids
.get_url_encoded_string()
.map_err(|err| {
logger::error!(?err);
UnifiedConnectorServiceError::HeaderInjectionFailed(consts::UCS_LINEAGE_IDS.to_string())
})?;
metadata.append(
consts::UCS_LINEAGE_IDS,
parse(consts::UCS_LINEAGE_IDS, &lineage_ids_str)?,
);
if let Some(reference_id) = grpc_headers.merchant_reference_id {
metadata.append(
consts::UCS_HEADER_REFERENCE_ID,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs | crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs | use api_models::routing::{
ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,
LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
};
use common_utils::{
ext_traits::OptionExt,
transformers::{ForeignFrom, ForeignTryFrom},
};
pub use contract_routing::{
contract_score_calculator_client::ContractScoreCalculatorClient, CalContractScoreConfig,
CalContractScoreRequest, CalContractScoreResponse, InvalidateContractRequest,
InvalidateContractResponse, LabelInformation as ProtoLabelInfo, TimeScale,
UpdateContractRequest, UpdateContractResponse,
};
use error_stack::ResultExt;
use router_env::logger;
use crate::grpc_client::{self, GrpcHeaders};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod contract_routing {
tonic::include_proto!("contract_routing");
}
pub use tonic::Code;
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
/// The trait ContractBasedDynamicRouting would have the functions required to support the calculation and updation window
#[async_trait::async_trait]
pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
/// To calculate the contract scores for the list of chosen connectors
async fn calculate_contract_score(
&self,
id: String,
config: ContractBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalContractScoreResponse>;
/// To update the contract scores with the given labels
async fn update_contracts(
&self,
id: String,
label_info: Vec<LabelInformation>,
params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
incr_count: u64,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateContractResponse>;
/// To invalidates the contract scores against the id
async fn invalidate_contracts(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateContractResponse>;
}
#[async_trait::async_trait]
impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {
async fn calculate_contract_score(
&self,
id: String,
config: ContractBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalContractScoreResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalContractScoreRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_contract_score(request)
.await
.map_err(|err| match err.code() {
Code::NotFound => DynamicRoutingError::ContractNotFound,
_ => DynamicRoutingError::ContractBasedRoutingFailure(err.to_string()),
})?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn update_contracts(
&self,
id: String,
label_info: Vec<LabelInformation>,
params: String,
_response: Vec<RoutableConnectorChoiceWithStatus>,
incr_count: u64,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateContractResponse> {
let mut labels_information = label_info
.into_iter()
.map(ProtoLabelInfo::foreign_from)
.collect::<Vec<_>>();
labels_information
.iter_mut()
.for_each(|info| info.current_count += incr_count);
let request = grpc_client::create_grpc_request(
UpdateContractRequest {
id,
params,
labels_information,
},
headers,
);
let response = self
.clone()
.update_contract(request)
.await
.change_context(DynamicRoutingError::ContractBasedRoutingFailure(
"Failed to update the contracts".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn invalidate_contracts(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateContractResponse> {
let request = grpc_client::create_grpc_request(InvalidateContractRequest { id }, headers);
let response = self
.clone()
.invalidate_contract(request)
.await
.change_context(DynamicRoutingError::ContractBasedRoutingFailure(
"Failed to invalidate the contracts".to_string(),
))?
.into_inner();
Ok(response)
}
}
impl ForeignFrom<ContractBasedTimeScale> for TimeScale {
fn foreign_from(scale: ContractBasedTimeScale) -> Self {
Self {
time_scale: match scale {
ContractBasedTimeScale::Day => 0,
_ => 1,
},
}
}
}
impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
constants: config
.constants
.get_required_value("constants")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "constants".to_string(),
})?,
time_scale: config.time_scale.clone().map(TimeScale::foreign_from),
})
}
}
impl ForeignFrom<LabelInformation> for ProtoLabelInfo {
fn foreign_from(config: LabelInformation) -> Self {
Self {
label: format!(
"{}:{}",
config.label.clone(),
config.mca_id.get_string_repr()
),
target_count: config.target_count,
target_time: config.target_time,
current_count: u64::default(),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs | crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs | use api_models::routing::{
CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, SuccessRateSpecificityLevel,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
pub use success_rate::{
success_rate_calculator_client::SuccessRateCalculatorClient, CalGlobalSuccessRateConfig,
CalGlobalSuccessRateRequest, CalGlobalSuccessRateResponse, CalSuccessRateConfig,
CalSuccessRateRequest, CalSuccessRateResponse,
CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
InvalidateWindowsResponse, LabelWithStatus,
SuccessRateSpecificityLevel as ProtoSpecificityLevel, UpdateSuccessRateWindowConfig,
UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod success_rate {
tonic::include_proto!("success_rate");
}
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
use crate::grpc_client::{self, GrpcHeaders};
/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window
#[async_trait::async_trait]
pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
/// To calculate the success rate for the list of chosen connectors
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse>;
/// To update the success rate with the given label
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
/// To invalidates the success rate routing keys
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse>;
/// To calculate both global and merchant specific success rate for the list of chosen connectors
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse>;
}
#[async_trait::async_trait]
impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
#[instrument(skip_all)]
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalSuccessRateRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let labels_with_status = label_input
.clone()
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.to_string(),
status: conn_choice.status,
})
.collect();
let global_labels_with_status = label_input
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.connector.to_string(),
status: conn_choice.status,
})
.collect();
let request = grpc_client::create_grpc_request(
UpdateSuccessRateWindowRequest {
id,
params,
labels_with_status,
config,
global_labels_with_status,
},
headers,
);
let response = self
.clone()
.update_success_rate_window(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to update the success rate window".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse> {
let request = grpc_client::create_grpc_request(InvalidateWindowsRequest { id }, headers);
let response = self
.clone()
.invalidate_windows(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to invalidate the success rate routing keys".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse> {
let labels = label_input
.clone()
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let global_labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.connector.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalGlobalSuccessRateRequest {
entity_id: id,
entity_params: params,
entity_labels: labels,
global_labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_entity_and_global_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the entity and global success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
}
impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> {
Ok(Self {
duration_in_mins: current_threshold.duration_in_mins,
max_total_count: current_threshold
.max_total_count
.get_required_value("max_total_count")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "max_total_count".to_string(),
})?,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
max_aggregates_size: config
.max_aggregates_size
.get_required_value("max_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "max_aggregates_size".to_string(),
})?,
current_block_threshold: config
.current_block_threshold
.map(ForeignTryFrom::foreign_try_from)
.transpose()?,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
specificity_level: match config.specificity_level {
SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()),
SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()),
},
exploration_percent: config.exploration_percent,
shuffle_on_tie_during_exploitation: config.shuffle_on_tie_during_exploitation,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalGlobalSuccessRateConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
entity_min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
entity_default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs | crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs | use api_models::routing::{
EliminationAnalyserConfig as EliminationConfig, RoutableConnectorChoice,
RoutableConnectorChoiceWithBucketName,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
pub use elimination_rate::{
elimination_analyser_client::EliminationAnalyserClient, EliminationBucketConfig,
EliminationRequest, EliminationResponse, InvalidateBucketRequest, InvalidateBucketResponse,
LabelWithBucketName, UpdateEliminationBucketRequest, UpdateEliminationBucketResponse,
};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod elimination_rate {
tonic::include_proto!("elimination");
}
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
use crate::grpc_client::{self, GrpcHeaders};
/// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket
#[async_trait::async_trait]
pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync {
/// To perform the elimination based routing for the list of connectors
async fn perform_elimination_routing(
&self,
id: String,
params: String,
labels: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse>;
/// To update the bucket size and ttl for list of connectors with its respective bucket name
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
config: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse>;
/// To invalidate the previous id's bucket
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse>;
}
#[async_trait::async_trait]
impl EliminationBasedRouting for EliminationAnalyserClient<Client> {
#[instrument(skip_all)]
async fn perform_elimination_routing(
&self,
id: String,
params: String,
label_input: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let request = grpc_client::create_grpc_request(
EliminationRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.get_elimination_status(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to perform the elimination analysis".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse> {
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let labels_with_bucket_name = report
.into_iter()
.map(|conn_choice_with_bucket| LabelWithBucketName {
label: conn_choice_with_bucket
.routable_connector_choice
.to_string(),
bucket_name: conn_choice_with_bucket.bucket_name,
})
.collect::<Vec<_>>();
let request = grpc_client::create_grpc_request(
UpdateEliminationBucketRequest {
id,
params,
labels_with_bucket_name,
config,
},
headers,
);
let response = self
.clone()
.update_elimination_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to update the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse> {
let request = grpc_client::create_grpc_request(InvalidateBucketRequest { id }, headers);
let response = self
.clone()
.invalidate_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to invalidate the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
}
impl ForeignTryFrom<EliminationConfig> for EliminationBucketConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: EliminationConfig) -> Result<Self, Self::Error> {
Ok(Self {
bucket_size: config
.bucket_size
.get_required_value("bucket_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_size".to_string(),
})?,
bucket_leak_interval_in_secs: config
.bucket_leak_interval_in_secs
.get_required_value("bucket_leak_interval_in_secs")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_leak_interval_in_secs".to_string(),
})?,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs | crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs | use std::fmt::Debug;
use common_utils::errors::CustomResult;
use error_stack::{Report, ResultExt};
use router_env::logger;
use crate::grpc_client::Client;
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod decider {
tonic::include_proto!("decider");
}
use decider::decider_client::DeciderClient;
pub use decider::{DeciderRequest, DeciderResponse};
/// Recovery Decider result
pub type RecoveryDeciderResult<T> = CustomResult<T, RecoveryDeciderError>;
/// Recovery Decider Error
#[derive(Debug, Clone, thiserror::Error)]
pub enum RecoveryDeciderError {
/// Error establishing gRPC connection
#[error("Failed to establish connection with Recovery Decider service: {0}")]
ConnectionError(String),
/// Error received from the gRPC service
#[error("Recovery Decider service returned an error: {0}")]
ServiceError(String),
/// Missing configuration for the client
#[error("Recovery Decider client configuration is missing or invalid")]
ConfigError(String),
}
/// Recovery Decider Client type
#[async_trait::async_trait]
pub trait RecoveryDeciderClientInterface: dyn_clone::DynClone + Send + Sync + Debug {
/// fn to call gRPC service
async fn decide_on_retry(
&mut self,
request_payload: DeciderRequest,
recovery_headers: super::GrpcRecoveryHeaders,
) -> RecoveryDeciderResult<DeciderResponse>;
}
dyn_clone::clone_trait_object!(RecoveryDeciderClientInterface);
/// Configuration for the Recovery Decider gRPC client.
#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)]
pub struct RecoveryDeciderClientConfig {
/// Base URL of the Recovery Decider service
pub base_url: String,
}
impl RecoveryDeciderClientConfig {
/// Validate the configuration
pub fn validate(&self) -> Result<(), RecoveryDeciderError> {
use common_utils::fp_utils::when;
when(self.base_url.is_empty(), || {
Err(RecoveryDeciderError::ConfigError(
"Recovery Decider base URL cannot be empty when configuration is provided"
.to_string(),
))
})
}
/// create a connection
pub fn get_recovery_decider_connection(
&self,
hyper_client: Client,
) -> Result<DeciderClient<Client>, Report<RecoveryDeciderError>> {
let uri = self
.base_url
.parse::<tonic::transport::Uri>()
.map_err(Report::from)
.change_context(RecoveryDeciderError::ConfigError(format!(
"Invalid URI: {}",
self.base_url
)))?;
let service_client = DeciderClient::with_origin(hyper_client, uri);
Ok(service_client)
}
}
#[async_trait::async_trait]
impl RecoveryDeciderClientInterface for DeciderClient<Client> {
async fn decide_on_retry(
&mut self,
request_payload: DeciderRequest,
recovery_headers: super::GrpcRecoveryHeaders,
) -> RecoveryDeciderResult<DeciderResponse> {
let request =
super::create_revenue_recovery_grpc_request(request_payload, recovery_headers);
logger::debug!(decider_request =?request);
let grpc_response = self
.decide(request)
.await
.change_context(RecoveryDeciderError::ServiceError(
"Decider service call failed".to_string(),
))?
.into_inner();
logger::debug!(grpc_decider_response =?grpc_response);
Ok(grpc_response)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/email/smtp.rs | crates/external_services/src/email/smtp.rs | use std::time::Duration;
use common_utils::{errors::CustomResult, pii};
use error_stack::ResultExt;
use lettre::{
address::AddressError,
error,
message::{header::ContentType, Mailbox},
transport::smtp::{self, authentication::Credentials},
Message, SmtpTransport, Transport,
};
use masking::{PeekInterface, Secret};
use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
/// Client for SMTP server operation
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct SmtpServer {
/// sender email id
pub sender: String,
/// SMTP server specific configs
pub smtp_config: SmtpServerConfig,
}
impl SmtpServer {
/// A helper function to create SMTP server client
pub fn create_client(&self) -> Result<SmtpTransport, SmtpError> {
let host = self.smtp_config.host.clone();
let port = self.smtp_config.port;
let timeout = Some(Duration::from_secs(self.smtp_config.timeout));
let credentials = self
.smtp_config
.username
.clone()
.zip(self.smtp_config.password.clone())
.map(|(username, password)| {
Credentials::new(username.peek().to_owned(), password.peek().to_owned())
});
match &self.smtp_config.connection {
SmtpConnection::StartTls => match credentials {
Some(credentials) => Ok(SmtpTransport::starttls_relay(&host)
.map_err(SmtpError::ConnectionFailure)?
.port(port)
.timeout(timeout)
.credentials(credentials)
.build()),
None => Ok(SmtpTransport::starttls_relay(&host)
.map_err(SmtpError::ConnectionFailure)?
.port(port)
.timeout(timeout)
.build()),
},
SmtpConnection::Plaintext => match credentials {
Some(credentials) => Ok(SmtpTransport::builder_dangerous(&host)
.port(port)
.timeout(timeout)
.credentials(credentials)
.build()),
None => Ok(SmtpTransport::builder_dangerous(&host)
.port(port)
.timeout(timeout)
.build()),
},
}
}
/// Constructs a new SMTP client
pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self {
Self {
sender: conf.sender_email.clone(),
smtp_config: smtp_config.clone(),
}
}
/// helper function to convert email id into Mailbox
fn to_mail_box(email: String) -> EmailResult<Mailbox> {
Ok(Mailbox::new(
None,
email
.parse()
.map_err(SmtpError::EmailParsingFailed)
.change_context(EmailError::EmailSendingFailure)?,
))
}
}
/// Struct that contains the SMTP server specific configs required
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct SmtpServerConfig {
/// hostname of the SMTP server eg: smtp.gmail.com
pub host: String,
/// portname of the SMTP server eg: 25
pub port: u16,
/// timeout for the SMTP server connection in seconds eg: 10
pub timeout: u64,
/// Username name of the SMTP server
pub username: Option<Secret<String>>,
/// Password of the SMTP server
pub password: Option<Secret<String>>,
/// Connection type of the SMTP server
#[serde(default)]
pub connection: SmtpConnection,
}
/// Enum that contains the connection types of the SMTP server
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SmtpConnection {
#[default]
/// Plaintext connection which MUST then successfully upgrade to TLS via STARTTLS
StartTls,
/// Plaintext connection (very insecure)
Plaintext,
}
impl SmtpServerConfig {
/// Validation for the SMTP server client specific configs
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.host.is_default_or_empty(), || {
Err("email.smtp.host must not be empty")
})?;
self.username.clone().zip(self.password.clone()).map_or(
Ok(()),
|(username, password)| {
when(username.peek().is_default_or_empty(), || {
Err("email.smtp.username must not be empty")
})?;
when(password.peek().is_default_or_empty(), || {
Err("email.smtp.password must not be empty")
})
},
)?;
Ok(())
}
}
#[async_trait::async_trait]
impl EmailClient for SmtpServer {
type RichText = String;
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
Ok(intermediate_string.into_inner())
}
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
_proxy_url: Option<&String>,
) -> EmailResult<()> {
// Create a client every time when the email is being sent
let email_client =
Self::create_client(self).change_context(EmailError::EmailSendingFailure)?;
let email = Message::builder()
.to(Self::to_mail_box(recipient.peek().to_string())?)
.from(Self::to_mail_box(self.sender.clone())?)
.subject(subject)
.header(ContentType::TEXT_HTML)
.body(body)
.map_err(SmtpError::MessageBuildingFailed)
.change_context(EmailError::EmailSendingFailure)?;
email_client
.send(&email)
.map_err(SmtpError::SendingFailure)
.change_context(EmailError::EmailSendingFailure)?;
Ok(())
}
}
/// Errors that could occur during SES operations.
#[derive(Debug, thiserror::Error)]
pub enum SmtpError {
/// An error occurred in the SMTP while sending email.
#[error("Failed to Send Email {0:?}")]
SendingFailure(smtp::Error),
/// An error occurred in the SMTP while building the message content.
#[error("Failed to create connection {0:?}")]
ConnectionFailure(smtp::Error),
/// An error occurred in the SMTP while building the message content.
#[error("Failed to Build Email content {0:?}")]
MessageBuildingFailed(error::Error),
/// An error occurred in the SMTP while building the message content.
#[error("Failed to parse given email {0:?}")]
EmailParsingFailed(AddressError),
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/email/no_email.rs | crates/external_services/src/email/no_email.rs | use common_utils::{errors::CustomResult, pii};
use router_env::logger;
use crate::email::{EmailClient, EmailError, EmailResult, IntermediateString};
/// Client when email support is disabled
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct NoEmailClient {}
impl NoEmailClient {
/// Constructs a new client when email is disabled
pub async fn create() -> Self {
Self {}
}
}
#[async_trait::async_trait]
impl EmailClient for NoEmailClient {
type RichText = String;
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
Ok(intermediate_string.into_inner())
}
async fn send_email(
&self,
_recipient: pii::Email,
_subject: String,
_body: Self::RichText,
_proxy_url: Option<&String>,
) -> EmailResult<()> {
logger::info!("Email not sent as email support is disabled, please enable any of the supported email clients to send emails");
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/email/ses.rs | crates/external_services/src/email/ses.rs | use std::time::{Duration, SystemTime};
use aws_sdk_sesv2::{
config::Region,
operation::send_email::SendEmailError,
types::{Body, Content, Destination, EmailContent, Message},
Client,
};
use aws_sdk_sts::config::Credentials;
use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
use common_utils::{errors::CustomResult, pii};
use error_stack::{report, ResultExt};
use hyper::Uri;
use masking::PeekInterface;
use router_env::logger;
use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
/// Client for AWS SES operation
#[derive(Debug, Clone)]
pub struct AwsSes {
sender: String,
ses_config: SESConfig,
settings: EmailSettings,
}
/// Struct that contains the AWS ses specific configs required to construct an SES email client
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct SESConfig {
/// The arn of email role
pub email_role_arn: String,
/// The name of sts_session role
pub sts_role_session_name: String,
}
impl SESConfig {
/// Validation for the SES client specific configs
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.email_role_arn.is_default_or_empty(), || {
Err("email.aws_ses.email_role_arn must not be empty")
})?;
when(self.sts_role_session_name.is_default_or_empty(), || {
Err("email.aws_ses.sts_role_session_name must not be empty")
})
}
}
/// Errors that could occur during SES operations.
#[derive(Debug, thiserror::Error)]
pub enum AwsSesError {
/// An error occurred in the SDK while sending email.
#[error("Failed to Send Email {0:?}")]
SendingFailure(Box<aws_sdk_sesv2::error::SdkError<SendEmailError>>),
/// Configuration variable is missing to construct the email client
#[error("Missing configuration variable {0}")]
MissingConfigurationVariable(&'static str),
/// Failed to assume the given STS role
#[error("Failed to STS assume role: Role ARN: {role_arn}, Session name: {session_name}, Region: {region}")]
AssumeRoleFailure {
/// Aws region
region: String,
/// arn of email role
role_arn: String,
/// The name of sts_session role
session_name: String,
},
/// Temporary credentials are missing
#[error("Assumed role does not contain credentials for role user: {0:?}")]
TemporaryCredentialsMissing(String),
/// The proxy Connector cannot be built
#[error("The proxy build cannot be built")]
BuildingProxyConnectorFailed,
}
impl AwsSes {
/// Constructs a new AwsSes client
pub async fn create(
conf: &EmailSettings,
ses_config: &SESConfig,
proxy_url: Option<impl AsRef<str>>,
) -> Self {
// Build the client initially which will help us know if the email configuration is correct
Self::create_client(conf, ses_config, proxy_url)
.await
.map_err(|error| logger::error!(?error, "Failed to initialize SES Client"))
.ok();
Self {
sender: conf.sender_email.clone(),
ses_config: ses_config.clone(),
settings: conf.clone(),
}
}
/// A helper function to create ses client
pub async fn create_client(
conf: &EmailSettings,
ses_config: &SESConfig,
proxy_url: Option<impl AsRef<str>>,
) -> CustomResult<Client, AwsSesError> {
let sts_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url.as_ref())?
.load()
.await;
let role = aws_sdk_sts::Client::new(&sts_config)
.assume_role()
.role_arn(&ses_config.email_role_arn)
.role_session_name(&ses_config.sts_role_session_name)
.send()
.await
.change_context(AwsSesError::AssumeRoleFailure {
region: conf.aws_region.to_owned(),
role_arn: ses_config.email_role_arn.to_owned(),
session_name: ses_config.sts_role_session_name.to_owned(),
})?;
let creds = role.credentials().ok_or(
report!(AwsSesError::TemporaryCredentialsMissing(format!(
"{role:?}"
)))
.attach_printable("Credentials object not available"),
)?;
let credentials = Credentials::new(
creds.access_key_id(),
creds.secret_access_key(),
Some(creds.session_token().to_owned()),
u64::try_from(creds.expiration().as_nanos())
.ok()
.map(Duration::from_nanos)
.and_then(|val| SystemTime::UNIX_EPOCH.checked_add(val)),
"custom_provider",
);
logger::debug!(
"Obtained SES temporary credentials with expiry {:?}",
credentials.expiry()
);
let ses_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url)?
.credentials_provider(credentials)
.load()
.await;
Ok(Client::new(&ses_config))
}
fn get_shared_config(
region: String,
proxy_url: Option<impl AsRef<str>>,
) -> CustomResult<aws_config::ConfigLoader, AwsSesError> {
let region_provider = Region::new(region);
let mut config = aws_config::from_env().region(region_provider);
if let Some(proxy_url) = proxy_url {
let proxy_connector = Self::get_proxy_connector(proxy_url)?;
let http_client = HyperClientBuilder::new().build(proxy_connector);
config = config.http_client(http_client);
};
Ok(config)
}
fn get_proxy_connector(
proxy_url: impl AsRef<str>,
) -> CustomResult<hyper_proxy::ProxyConnector<hyper::client::HttpConnector>, AwsSesError> {
let proxy_uri = proxy_url
.as_ref()
.parse::<Uri>()
.attach_printable("Unable to parse the proxy url {proxy_url}")
.change_context(AwsSesError::BuildingProxyConnectorFailed)?;
let proxy = hyper_proxy::Proxy::new(hyper_proxy::Intercept::All, proxy_uri);
hyper_proxy::ProxyConnector::from_proxy(hyper::client::HttpConnector::new(), proxy)
.change_context(AwsSesError::BuildingProxyConnectorFailed)
}
}
#[async_trait::async_trait]
impl EmailClient for AwsSes {
type RichText = Body;
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
let email_body = Body::builder()
.html(
Content::builder()
.data(intermediate_string.into_inner())
.charset("UTF-8")
.build()
.change_context(EmailError::ContentBuildFailure)?,
)
.build();
Ok(email_body)
}
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
proxy_url: Option<&String>,
) -> EmailResult<()> {
// Not using the same email client which was created at startup as the role session would expire
// Create a client every time when the email is being sent
let email_client = Self::create_client(&self.settings, &self.ses_config, proxy_url)
.await
.change_context(EmailError::ClientBuildingFailure)?;
email_client
.send_email()
.from_email_address(self.sender.to_owned())
.destination(
Destination::builder()
.to_addresses(recipient.peek())
.build(),
)
.content(
EmailContent::builder()
.simple(
Message::builder()
.subject(
Content::builder()
.data(subject)
.build()
.change_context(EmailError::ContentBuildFailure)?,
)
.body(body)
.build(),
)
.build(),
)
.send()
.await
.map_err(|e| AwsSesError::SendingFailure(Box::new(e)))
.change_context(EmailError::EmailSendingFailure)?;
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/aws_kms/core.rs | crates/external_services/src/aws_kms/core.rs | //! Interactions with the AWS KMS SDK
use std::time::Instant;
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::{config::Region, primitives::Blob, Client};
use base64::Engine;
use common_utils::errors::CustomResult;
use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{consts, metrics};
/// Configuration parameters required for constructing a [`AwsKmsClient`].
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[serde(default)]
pub struct AwsKmsConfig {
/// The AWS key identifier of the KMS key used to encrypt or decrypt data.
pub key_id: Option<String>,
/// The AWS region to send KMS requests to.
pub region: String,
}
/// Client for AWS KMS operations.
#[derive(Debug, Clone)]
pub struct AwsKmsClient {
inner_client: Client,
key_id: Option<String>,
}
impl AwsKmsClient {
/// Constructs a new AWS KMS client.
pub async fn new(config: &AwsKmsConfig) -> Self {
let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
let sdk_config = aws_config::from_env().region(region_provider).load().await;
Self {
inner_client: Client::new(&sdk_config),
key_id: config.key_id.clone(),
}
}
/// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that
/// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
/// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
/// a machine that is able to assume an IAM role.
pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
let start = Instant::now();
let data = consts::BASE64_ENGINE
.decode(data)
.change_context(AwsKmsError::Base64DecodingFailed)?;
let ciphertext_blob = Blob::new(data);
let mut decryption_builder = self.inner_client.decrypt();
if let Some(key_id) = &self.key_id {
decryption_builder = decryption_builder.key_id(key_id);
}
let decrypt_output = decryption_builder
.ciphertext_blob(ciphertext_blob)
.send()
.await
.inspect_err(|error| {
// Logging using `Debug` representation of the error as the `Display`
// representation does not hold sufficient information.
logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data");
metrics::AWS_KMS_DECRYPTION_FAILURES.add(1, &[]);
})
.change_context(AwsKmsError::DecryptionFailed)?;
let output = decrypt_output
.plaintext
.ok_or(report!(AwsKmsError::MissingPlaintextDecryptionOutput))
.and_then(|blob| {
String::from_utf8(blob.into_inner()).change_context(AwsKmsError::Utf8DecodingFailed)
})?;
let time_taken = start.elapsed();
metrics::AWS_KMS_DECRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
Ok(output)
}
/// Encrypts the provided String data using the AWS KMS SDK. We assume that
/// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
/// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
/// a machine that is able to assume an IAM role.
pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
let start = Instant::now();
let plaintext_blob = Blob::new(data.as_ref());
let mut encryption_builder = self.inner_client.encrypt();
match &self.key_id {
Some(key_id) => encryption_builder = encryption_builder.key_id(key_id),
None => {
return Err(report!(AwsKmsError::MissingKeyId));
}
};
let encrypted_output = encryption_builder
.plaintext(plaintext_blob)
.send()
.await
.inspect_err(|error| {
// Logging using `Debug` representation of the error as the `Display`
// representation does not hold sufficient information.
logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data");
metrics::AWS_KMS_ENCRYPTION_FAILURES.add(1, &[]);
})
.change_context(AwsKmsError::EncryptionFailed)?;
let output = encrypted_output
.ciphertext_blob
.ok_or(AwsKmsError::MissingCiphertextEncryptionOutput)
.map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?;
let time_taken = start.elapsed();
metrics::AWS_KMS_ENCRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
Ok(output)
}
}
/// Errors that could occur during KMS operations.
#[derive(Debug, thiserror::Error)]
pub enum AwsKmsError {
/// An error occurred when base64 encoding input data.
#[error("Failed to base64 encode input data")]
Base64EncodingFailed,
/// An error occurred when base64 decoding input data.
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
/// An error occurred when AWS KMS decrypting input data.
#[error("Failed to AWS KMS decrypt input data")]
DecryptionFailed,
/// An error occurred when AWS KMS encrypting input data.
#[error("Failed to AWS KMS encrypt input data")]
EncryptionFailed,
/// The AWS KMS decrypted output does not include a plaintext output.
#[error("Missing plaintext AWS KMS decryption output")]
MissingPlaintextDecryptionOutput,
/// The AWS KMS encrypted output does not include a ciphertext output.
#[error("Missing ciphertext AWS KMS encryption output")]
MissingCiphertextEncryptionOutput,
/// An error occurred UTF-8 decoding AWS KMS decrypted output.
#[error("Failed to UTF-8 decode decryption output")]
Utf8DecodingFailed,
/// The AWS KMS client has not been initialized.
#[error("The AWS KMS client has not been initialized")]
AwsKmsClientNotInitialized,
/// AWS KMS key id not provided.
#[error("AWS KMS key id not provided")]
MissingKeyId,
}
impl AwsKmsConfig {
/// Verifies that the [`AwsKmsClient`] configuration is usable.
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.region.is_default_or_empty(), || {
Err("KMS AWS region must not be empty")
})
}
}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn check_aws_kms_encryption() {
std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
use super::*;
let config = AwsKmsConfig {
key_id: Some("YOUR AWS KMS KEY ID".to_string()),
region: "AWS REGION".to_string(),
};
let data = "hello".to_string();
let binding = data.as_bytes();
let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
.await
.encrypt(binding)
.await
.expect("aws kms encryption failed");
println!("{kms_encrypted_fingerprint}");
}
#[tokio::test]
async fn check_aws_kms_decrypt() {
std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
use super::*;
let config = AwsKmsConfig {
key_id: Some("YOUR AWS KMS KEY ID".to_string()),
region: "AWS REGION".to_string(),
};
// Should decrypt to hello
let data = "AWS KMS ENCRYPTED CIPHER".to_string();
let binding = data.as_bytes();
let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
.await
.decrypt(binding)
.await
.expect("aws kms decryption failed");
println!("{kms_encrypted_fingerprint}");
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/aws_kms/implementers.rs | crates/external_services/src/aws_kms/implementers.rs | //! Trait implementations for aws kms client
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::{
encryption_interface::{EncryptionError, EncryptionManagementInterface},
secrets_interface::{SecretManagementInterface, SecretsManagementError},
};
use masking::{PeekInterface, Secret};
use crate::aws_kms::core::AwsKmsClient;
#[async_trait::async_trait]
impl EncryptionManagementInterface for AwsKmsClient {
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
self.encrypt(input)
.await
.change_context(EncryptionError::EncryptionFailed)
.map(|val| val.into_bytes())
}
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
self.decrypt(input)
.await
.change_context(EncryptionError::DecryptionFailed)
.map(|val| val.into_bytes())
}
}
#[async_trait::async_trait]
impl SecretManagementInterface for AwsKmsClient {
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
self.decrypt(input.peek())
.await
.change_context(SecretsManagementError::FetchSecretFailed)
.map(Into::into)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/hashicorp_vault/core.rs | crates/external_services/src/hashicorp_vault/core.rs | //! Interactions with the HashiCorp Vault
use std::{collections::HashMap, future::Future, pin::Pin};
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
use error_stack::{Report, ResultExt};
use masking::{PeekInterface, Secret};
use vaultrs::client::{VaultClient, VaultClientSettingsBuilder};
static HC_CLIENT: tokio::sync::OnceCell<HashiCorpVault> = tokio::sync::OnceCell::const_new();
#[allow(missing_debug_implementations)]
/// A struct representing a connection to HashiCorp Vault.
pub struct HashiCorpVault {
/// The underlying client used for interacting with HashiCorp Vault.
client: VaultClient,
}
/// Configuration for connecting to HashiCorp Vault.
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[serde(default)]
pub struct HashiCorpVaultConfig {
/// The URL of the HashiCorp Vault server.
pub url: String,
/// The authentication token used to access HashiCorp Vault.
pub token: Secret<String>,
}
impl HashiCorpVaultConfig {
/// Verifies that the [`HashiCorpVault`] configuration is usable.
pub fn validate(&self) -> Result<(), &'static str> {
when(self.url.is_default_or_empty(), || {
Err("HashiCorp vault url must not be empty")
})?;
when(self.token.is_default_or_empty(), || {
Err("HashiCorp vault token must not be empty")
})
}
}
/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration.
///
/// # Parameters
///
/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
pub async fn get_hashicorp_client(
config: &HashiCorpVaultConfig,
) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> {
HC_CLIENT
.get_or_try_init(|| async { HashiCorpVault::new(config) })
.await
}
/// A trait defining an engine for interacting with HashiCorp Vault.
pub trait Engine: Sized {
/// The associated type representing the return type of the engine's operations.
type ReturnType<'b, T>
where
T: 'b,
Self: 'b;
/// Reads data from HashiCorp Vault at the specified location.
///
/// # Parameters
///
/// - `client`: A reference to the HashiCorpVault client.
/// - `location`: The location in HashiCorp Vault to read data from.
///
/// # Returns
///
/// A future representing the result of the read operation.
fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String>;
}
/// An implementation of the `Engine` trait for the Key-Value version 2 (Kv2) engine.
#[derive(Debug)]
pub enum Kv2 {}
impl Engine for Kv2 {
type ReturnType<'b, T: 'b> =
Pin<Box<dyn Future<Output = error_stack::Result<T, HashiCorpError>> + Send + 'b>>;
fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String> {
Box::pin(async move {
let mut split = location.split(':');
let mount = split.next().ok_or(HashiCorpError::IncompleteData)?;
let path = split.next().ok_or(HashiCorpError::IncompleteData)?;
let key = split.next().unwrap_or("value");
let mut output =
vaultrs::kv2::read::<HashMap<String, String>>(&client.client, mount, path)
.await
.map_err(Into::<Report<_>>::into)
.change_context(HashiCorpError::FetchFailed)?;
Ok(output.remove(key).ok_or(HashiCorpError::ParseError)?)
})
}
}
impl HashiCorpVault {
/// Creates a new instance of HashiCorpVault based on the provided configuration.
///
/// # Parameters
///
/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> {
VaultClient::new(
VaultClientSettingsBuilder::default()
.address(&config.url)
.token(config.token.peek())
.build()
.map_err(Into::<Report<_>>::into)
.change_context(HashiCorpError::ClientCreationFailed)
.attach_printable("Failed while building vault settings")?,
)
.map_err(Into::<Report<_>>::into)
.change_context(HashiCorpError::ClientCreationFailed)
.map(|client| Self { client })
}
/// Asynchronously fetches data from HashiCorp Vault using the specified engine.
///
/// # Parameters
///
/// - `data`: A String representing the location or identifier of the data in HashiCorp Vault.
///
/// # Type Parameters
///
/// - `En`: The engine type that implements the `Engine` trait.
/// - `I`: The type that can be constructed from the retrieved encoded data.
pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError>
where
for<'a> En: Engine<
ReturnType<'a, String> = Pin<
Box<
dyn Future<Output = error_stack::Result<String, HashiCorpError>>
+ Send
+ 'a,
>,
>,
> + 'a,
I: FromEncoded,
{
let output = En::read(self, data).await?;
I::from_encoded(output).ok_or(error_stack::report!(HashiCorpError::HexDecodingFailed))
}
}
/// A trait for types that can be constructed from encoded data in the form of a String.
pub trait FromEncoded: Sized {
/// Constructs an instance of the type from the provided encoded input.
///
/// # Parameters
///
/// - `input`: A String containing the encoded data.
///
/// # Returns
///
/// An `Option<Self>` representing the constructed instance if successful, or `None` otherwise.
///
/// # Example
///
/// ```rust
/// use external_services::hashicorp_vault::core::FromEncoded;
/// use masking::Secret;
/// let secret_instance = Secret::<String>::from_encoded("encoded_secret_string".to_string());
/// let vec_instance = Vec::<u8>::from_encoded("68656c6c6f".to_string());
/// ```
fn from_encoded(input: String) -> Option<Self>;
}
impl FromEncoded for Secret<String> {
fn from_encoded(input: String) -> Option<Self> {
Some(input.into())
}
}
impl FromEncoded for Vec<u8> {
fn from_encoded(input: String) -> Option<Self> {
hex::decode(input).ok()
}
}
/// An enumeration representing various errors that can occur in interactions with HashiCorp Vault.
#[derive(Debug, thiserror::Error)]
pub enum HashiCorpError {
/// Failed while creating hashicorp client
#[error("Failed while creating a new client")]
ClientCreationFailed,
/// Failed while building configurations for hashicorp client
#[error("Failed while building configuration")]
ConfigurationBuildFailed,
/// Failed while decoding data to hex format
#[error("Failed while decoding hex data")]
HexDecodingFailed,
/// An error occurred when base64 decoding input data.
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
/// An error occurred when KMS decrypting input data.
#[error("Failed to KMS decrypt input data")]
DecryptionFailed,
/// The KMS decrypted output does not include a plaintext output.
#[error("Missing plaintext KMS decryption output")]
MissingPlaintextDecryptionOutput,
/// An error occurred UTF-8 decoding KMS decrypted output.
#[error("Failed to UTF-8 decode decryption output")]
Utf8DecodingFailed,
/// Incomplete data provided to fetch data from hasicorp
#[error("Provided information about the value is incomplete")]
IncompleteData,
/// Failed while fetching data from vault
#[error("Failed while fetching data from the server")]
FetchFailed,
/// Failed while parsing received data
#[error("Failed while parsing the response")]
ParseError,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/hashicorp_vault/implementers.rs | crates/external_services/src/hashicorp_vault/implementers.rs | //! Trait implementations for Hashicorp vault client
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::{
SecretManagementInterface, SecretsManagementError,
};
use masking::{ExposeInterface, Secret};
use crate::hashicorp_vault::core::{HashiCorpVault, Kv2};
#[async_trait::async_trait]
impl SecretManagementInterface for HashiCorpVault {
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
self.fetch::<Kv2, Secret<String>>(input.expose())
.await
.map(|val| val.expose().to_owned())
.change_context(SecretsManagementError::FetchSecretFailed)
.map(Into::into)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/file_storage/file_system.rs | crates/external_services/src/file_storage/file_system.rs | //! Module for local file system storage operations
use std::{
fs::{remove_file, File},
io::{Read, Write},
path::PathBuf,
};
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use crate::file_storage::{FileStorageError, FileStorageInterface};
/// Constructs the file path for a given file key within the file system.
/// The file path is generated based on the workspace path and the provided file key.
fn get_file_path(file_key: impl AsRef<str>) -> PathBuf {
let mut file_path = PathBuf::new();
file_path.push(std::env::current_dir().unwrap_or(".".into()));
file_path.push("files");
file_path.push(file_key.as_ref());
file_path
}
/// Represents a file system for storing and managing files locally.
#[derive(Debug, Clone)]
pub(super) struct FileSystem;
impl FileSystem {
/// Saves the provided file data to the file system under the specified file key.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileSystemStorageError> {
let file_path = get_file_path(file_key);
// Ignore the file name and create directories in the `file_path` if not exists
std::fs::create_dir_all(
file_path
.parent()
.ok_or(FileSystemStorageError::CreateDirFailed)
.attach_printable("Failed to obtain parent directory")?,
)
.change_context(FileSystemStorageError::CreateDirFailed)?;
let mut file_handler =
File::create(file_path).change_context(FileSystemStorageError::CreateFailure)?;
file_handler
.write_all(&file)
.change_context(FileSystemStorageError::WriteFailure)?;
Ok(())
}
/// Deletes the file associated with the specified file key from the file system.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileSystemStorageError> {
let file_path = get_file_path(file_key);
remove_file(file_path).change_context(FileSystemStorageError::DeleteFailure)?;
Ok(())
}
/// Retrieves the file content associated with the specified file key from the file system.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileSystemStorageError> {
let mut received_data: Vec<u8> = Vec::new();
let file_path = get_file_path(file_key);
let mut file =
File::open(file_path).change_context(FileSystemStorageError::FileOpenFailure)?;
file.read_to_end(&mut received_data)
.change_context(FileSystemStorageError::ReadFailure)?;
Ok(received_data)
}
}
#[async_trait::async_trait]
impl FileStorageInterface for FileSystem {
/// Saves the provided file data to the file system under the specified file key.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
self.upload_file(file_key, file)
.await
.change_context(FileStorageError::UploadFailed)?;
Ok(())
}
/// Deletes the file associated with the specified file key from the file system.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
self.delete_file(file_key)
.await
.change_context(FileStorageError::DeleteFailed)?;
Ok(())
}
/// Retrieves the file content associated with the specified file key from the file system.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
Ok(self
.retrieve_file(file_key)
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
}
/// Represents an error that can occur during local file system storage operations.
#[derive(Debug, thiserror::Error)]
enum FileSystemStorageError {
/// Error indicating opening a file failed
#[error("Failed while opening the file")]
FileOpenFailure,
/// Error indicating file creation failed.
#[error("Failed to create file")]
CreateFailure,
/// Error indicating reading a file failed.
#[error("Failed while reading the file")]
ReadFailure,
/// Error indicating writing to a file failed.
#[error("Failed while writing into file")]
WriteFailure,
/// Error indicating file deletion failed.
#[error("Failed while deleting the file")]
DeleteFailure,
/// Error indicating directory creation failed
#[error("Failed while creating a directory")]
CreateDirFailed,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/file_storage/aws_s3.rs | crates/external_services/src/file_storage/aws_s3.rs | use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{
operation::{
delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError,
},
Client,
};
use aws_sdk_sts::config::Region;
use common_utils::{errors::CustomResult, ext_traits::ConfigExt};
use error_stack::ResultExt;
use super::InvalidFileStorageConfig;
use crate::file_storage::{FileStorageError, FileStorageInterface};
/// Configuration for AWS S3 file storage.
#[derive(Debug, serde::Deserialize, Clone, Default)]
#[serde(default)]
pub struct AwsFileStorageConfig {
/// The AWS region to send file uploads
region: String,
/// The AWS s3 bucket to send file uploads
bucket_name: String,
}
impl AwsFileStorageConfig {
/// Validates the AWS S3 file storage configuration.
pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
use common_utils::fp_utils::when;
when(self.region.is_default_or_empty(), || {
Err(InvalidFileStorageConfig("aws s3 region must not be empty"))
})?;
when(self.bucket_name.is_default_or_empty(), || {
Err(InvalidFileStorageConfig(
"aws s3 bucket name must not be empty",
))
})
}
}
/// AWS S3 file storage client.
#[derive(Debug, Clone)]
pub(super) struct AwsFileStorageClient {
/// AWS S3 client
inner_client: Client,
/// The name of the AWS S3 bucket.
bucket_name: String,
}
impl AwsFileStorageClient {
/// Creates a new AWS S3 file storage client.
pub(super) async fn new(config: &AwsFileStorageConfig) -> Self {
let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
let sdk_config = aws_config::from_env().region(region_provider).load().await;
Self {
inner_client: Client::new(&sdk_config),
bucket_name: config.bucket_name.clone(),
}
}
/// Uploads a file to AWS S3.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), AwsS3StorageError> {
self.inner_client
.put_object()
.bucket(&self.bucket_name)
.key(file_key)
.body(file.into())
.send()
.await
.map_err(AwsS3StorageError::UploadFailure)?;
Ok(())
}
/// Deletes a file from AWS S3.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> {
self.inner_client
.delete_object()
.bucket(&self.bucket_name)
.key(file_key)
.send()
.await
.map_err(AwsS3StorageError::DeleteFailure)?;
Ok(())
}
/// Retrieves a file from AWS S3.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> {
Ok(self
.inner_client
.get_object()
.bucket(&self.bucket_name)
.key(file_key)
.send()
.await
.map_err(AwsS3StorageError::RetrieveFailure)?
.body
.collect()
.await
.map_err(AwsS3StorageError::UnknownError)?
.to_vec())
}
}
#[async_trait::async_trait]
impl FileStorageInterface for AwsFileStorageClient {
/// Uploads a file to AWS S3.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
self.upload_file(file_key, file)
.await
.change_context(FileStorageError::UploadFailed)?;
Ok(())
}
/// Deletes a file from AWS S3.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
self.delete_file(file_key)
.await
.change_context(FileStorageError::DeleteFailed)?;
Ok(())
}
/// Retrieves a file from AWS S3.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
Ok(self
.retrieve_file(file_key)
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
}
/// Enum representing errors that can occur during AWS S3 file storage operations.
#[derive(Debug, thiserror::Error)]
enum AwsS3StorageError {
/// Error indicating that file upload to S3 failed.
#[error("File upload to S3 failed: {0:?}")]
UploadFailure(aws_sdk_s3::error::SdkError<PutObjectError>),
/// Error indicating that file retrieval from S3 failed.
#[error("File retrieve from S3 failed: {0:?}")]
RetrieveFailure(aws_sdk_s3::error::SdkError<GetObjectError>),
/// Error indicating that file deletion from S3 failed.
#[error("File delete from S3 failed: {0:?}")]
DeleteFailure(aws_sdk_s3::error::SdkError<DeleteObjectError>),
/// Unknown error occurred.
#[error("Unknown error occurred: {0:?}")]
UnknownError(aws_sdk_s3::primitives::ByteStreamError),
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/http_client/client.rs | crates/external_services/src/http_client/client.rs | use std::{collections::HashMap, sync::RwLock, time::Duration};
use base64::Engine;
use common_utils::consts::BASE64_ENGINE;
pub use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::{errors::HttpClientError, types::Proxy};
use masking::ExposeInterface;
use once_cell::sync::OnceCell;
static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
static PROXY_CLIENT_CACHE: OnceCell<RwLock<HashMap<Proxy, reqwest::Client>>> = OnceCell::new();
use router_env::logger;
use super::metrics;
trait ProxyClientCacheKey {
fn cache_key(&self) -> Option<Proxy>;
}
// We may need to use outbound proxy to connect to external world.
// Precedence will be the environment variables, followed by the config.
#[allow(missing_docs)]
pub fn create_client(
proxy_config: &Proxy,
client_certificate: Option<masking::Secret<String>>,
client_certificate_key: Option<masking::Secret<String>>,
ca_certificate: Option<masking::Secret<String>>,
) -> CustomResult<reqwest::Client, HttpClientError> {
// Case 1: Mutual TLS with client certificate and key
if let (Some(encoded_certificate), Some(encoded_certificate_key)) =
(client_certificate.clone(), client_certificate_key.clone())
{
if ca_certificate.is_some() {
logger::warn!("All of client certificate, client key, and CA certificate are provided. CA certificate will be ignored in mutual TLS setup.");
}
logger::debug!("Creating HTTP client with mutual TLS (client cert + key)");
let client_builder =
apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config);
let identity = create_identity_from_certificate_and_key(
encoded_certificate.clone(),
encoded_certificate_key,
)?;
let certificate_list = create_certificate(encoded_certificate)?;
let client_builder = certificate_list
.into_iter()
.fold(client_builder, |client_builder, certificate| {
client_builder.add_root_certificate(certificate)
});
return client_builder
.identity(identity)
.use_rustls_tls()
.build()
.change_context(HttpClientError::ClientConstructionFailed)
.attach_printable("Failed to construct client with certificate and certificate key");
}
// Case 2: Use provided CA certificate for server authentication only (one-way TLS)
if let Some(ca_pem) = ca_certificate {
logger::debug!("Creating HTTP client with one-way TLS (CA certificate)");
let pem = ca_pem.expose().replace("\\r\\n", "\n"); // Fix escaped newlines
let cert = reqwest::Certificate::from_pem(pem.as_bytes())
.change_context(HttpClientError::ClientConstructionFailed)
.attach_printable("Failed to parse CA certificate PEM block")?;
let client_builder =
apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config)
.add_root_certificate(cert);
return client_builder
.use_rustls_tls()
.build()
.change_context(HttpClientError::ClientConstructionFailed)
.attach_printable("Failed to construct client with CA certificate");
}
// Case 3: Default client (no certs)
logger::debug!("Creating default HTTP client (no client or CA certificates)");
get_base_client(proxy_config)
}
#[allow(missing_docs)]
pub fn get_client_builder(
proxy_config: &Proxy,
) -> CustomResult<reqwest::ClientBuilder, HttpClientError> {
let mut client_builder = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.pool_idle_timeout(Duration::from_secs(
proxy_config
.idle_pool_connection_timeout
.unwrap_or_default(),
));
let proxy_exclusion_config =
reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default());
logger::debug!(
"Proxy HTTP Proxy -> {:?} and HTTPS Proxy -> {:?}",
proxy_config.http_url.clone(),
proxy_config.https_url.clone()
);
// Proxy all HTTPS traffic through the configured HTTPS proxy
if let Some(url) = proxy_config.https_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::https(url)
.change_context(HttpClientError::InvalidProxyConfiguration)
.attach_printable("HTTPS proxy configuration error")?
.no_proxy(proxy_exclusion_config.clone()),
);
}
// Proxy all HTTP traffic through the configured HTTP proxy
if let Some(url) = proxy_config.http_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::http(url)
.change_context(HttpClientError::InvalidProxyConfiguration)
.attach_printable("HTTP proxy configuration error")?
.no_proxy(proxy_exclusion_config),
);
}
Ok(client_builder)
}
#[allow(missing_docs)]
pub fn create_identity_from_certificate_and_key(
encoded_certificate: masking::Secret<String>,
encoded_certificate_key: masking::Secret<String>,
) -> Result<reqwest::Identity, error_stack::Report<HttpClientError>> {
let decoded_certificate = BASE64_ENGINE
.decode(encoded_certificate.expose())
.change_context(HttpClientError::CertificateDecodeFailed)?;
let decoded_certificate_key = BASE64_ENGINE
.decode(encoded_certificate_key.expose())
.change_context(HttpClientError::CertificateDecodeFailed)?;
let certificate = String::from_utf8(decoded_certificate)
.change_context(HttpClientError::CertificateDecodeFailed)?;
let certificate_key = String::from_utf8(decoded_certificate_key)
.change_context(HttpClientError::CertificateDecodeFailed)?;
let key_chain = format!("{certificate_key}{certificate}");
reqwest::Identity::from_pem(key_chain.as_bytes())
.change_context(HttpClientError::CertificateDecodeFailed)
}
#[allow(missing_docs)]
pub fn create_certificate(
encoded_certificate: masking::Secret<String>,
) -> Result<Vec<reqwest::Certificate>, error_stack::Report<HttpClientError>> {
let decoded_certificate = BASE64_ENGINE
.decode(encoded_certificate.expose())
.change_context(HttpClientError::CertificateDecodeFailed)?;
let certificate = String::from_utf8(decoded_certificate)
.change_context(HttpClientError::CertificateDecodeFailed)?;
reqwest::Certificate::from_pem_bundle(certificate.as_bytes())
.change_context(HttpClientError::CertificateDecodeFailed)
}
fn apply_mitm_certificate(
mut client_builder: reqwest::ClientBuilder,
proxy_config: &Proxy,
) -> reqwest::ClientBuilder {
if let Some(mitm_ca_cert) = &proxy_config.mitm_ca_certificate {
let pem = mitm_ca_cert.clone().expose().replace("\\r\\n", "\n");
match reqwest::Certificate::from_pem(pem.as_bytes()) {
Ok(cert) => {
logger::debug!("Successfully added MITM CA certificate");
client_builder = client_builder.add_root_certificate(cert);
}
Err(err) => {
logger::error!(
"Failed to parse MITM CA certificate: {}, continuing without MITM support",
err
);
}
}
}
client_builder
}
impl ProxyClientCacheKey for Proxy {
fn cache_key(&self) -> Option<Proxy> {
if self.has_proxy_config() {
logger::debug!("Using proxy config as cache key: {:?}", self);
// Return a clone of the proxy config for caching
// Exclude timeout from cache key by creating a normalized version
Some(Self {
http_url: self.http_url.clone(),
https_url: self.https_url.clone(),
bypass_proxy_hosts: self.bypass_proxy_hosts.clone(),
mitm_ca_certificate: self.mitm_ca_certificate.clone(),
idle_pool_connection_timeout: None, // Exclude timeout from cache key
mitm_enabled: self.mitm_enabled,
})
} else {
None
}
}
}
fn get_or_create_proxy_client(
cache: &RwLock<HashMap<Proxy, reqwest::Client>>,
cache_key: Proxy,
proxy_config: &Proxy,
metrics_tag: &[router_env::opentelemetry::KeyValue],
) -> CustomResult<reqwest::Client, HttpClientError> {
let read_result = cache
.read()
.ok()
.and_then(|read_lock| read_lock.get(&cache_key).cloned());
let client = match read_result {
Some(cached_client) => {
logger::debug!("Retrieved cached proxy client for config: {:?}", cache_key);
metrics::HTTP_CLIENT_CACHE_HIT.add(1, metrics_tag);
cached_client
}
None => {
let mut write_lock = cache.try_write().map_err(|_| {
error_stack::Report::new(HttpClientError::ClientConstructionFailed)
.attach_printable("Failed to acquire proxy client cache write lock")
})?;
match write_lock.get(&cache_key) {
Some(cached_client) => {
logger::debug!(
"Retrieved cached proxy client after write lock for config: {:?}",
cache_key
);
metrics::HTTP_CLIENT_CACHE_HIT.add(1, metrics_tag);
cached_client.clone()
}
None => {
logger::info!("Creating new proxy client for config: {:?}", cache_key);
metrics::HTTP_CLIENT_CACHE_MISS.add(1, metrics_tag);
let new_client =
apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config)
.build()
.change_context(HttpClientError::ClientConstructionFailed)
.attach_printable("Failed to construct proxy client")?;
metrics::HTTP_CLIENT_CREATED.add(1, metrics_tag);
write_lock.insert(cache_key.clone(), new_client.clone());
logger::debug!("Cached new proxy client for config: {:?}", cache_key);
new_client
}
}
}
};
Ok(client)
}
fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, HttpClientError> {
// Check if proxy configuration is provided using trait method
if let Some(cache_key) = proxy_config.cache_key() {
logger::debug!(
"Using proxy-specific client cache with key: {:?}",
cache_key
);
let metrics_tag = router_env::metric_attributes!(("client_type", "proxy"));
let cache = PROXY_CLIENT_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
let client = get_or_create_proxy_client(cache, cache_key, proxy_config, metrics_tag)?;
Ok(client)
} else {
logger::debug!("No proxy configuration detected, using DEFAULT_CLIENT");
let metrics_tag = router_env::metric_attributes!(("client_type", "default"));
// Use DEFAULT_CLIENT for non-proxy scenarios
let client = DEFAULT_CLIENT
.get_or_try_init(|| {
logger::info!("Initializing DEFAULT_CLIENT (no proxy configuration)");
metrics::HTTP_CLIENT_CREATED.add(1, metrics_tag);
apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config)
.build()
.change_context(HttpClientError::ClientConstructionFailed)
.attach_printable("Failed to construct default client")
})?
.clone();
metrics::HTTP_CLIENT_CACHE_HIT.add(1, metrics_tag);
Ok(client)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/http_client/metrics.rs | crates/external_services/src/http_client/metrics.rs | use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
histogram_metric_f64!(EXTERNAL_REQUEST_TIME, GLOBAL_METER);
counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER);
// HTTP Client creation metrics
counter_metric!(HTTP_CLIENT_CREATED, GLOBAL_METER);
counter_metric!(HTTP_CLIENT_CACHE_HIT, GLOBAL_METER);
counter_metric!(HTTP_CLIENT_CACHE_MISS, GLOBAL_METER);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/http_client/request.rs | crates/external_services/src/http_client/request.rs | use std::str::FromStr;
use common_utils::request::Headers;
pub use common_utils::{errors::CustomResult, request::ContentType};
use error_stack::ResultExt;
use hyperswitch_interfaces::errors::HttpClientError;
pub use masking::{Mask, Maskable};
use router_env::{instrument, tracing};
#[allow(missing_docs)]
pub trait HeaderExt {
fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, HttpClientError>;
}
impl HeaderExt for Headers {
fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, HttpClientError> {
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
self.into_iter().try_fold(
HeaderMap::new(),
|mut header_map, (header_name, header_value)| {
let header_name = HeaderName::from_str(&header_name)
.change_context(HttpClientError::HeaderMapConstructionFailed)?;
let header_value = header_value.into_inner();
let header_value = HeaderValue::from_str(&header_value)
.change_context(HttpClientError::HeaderMapConstructionFailed)?;
header_map.append(header_name, header_value);
Ok(header_map)
},
)
}
}
#[allow(missing_docs)]
pub trait RequestBuilderExt {
fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self;
}
impl RequestBuilderExt for reqwest::RequestBuilder {
#[instrument(skip_all)]
fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self {
self = self.headers(headers);
self
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/no_encryption/core.rs | crates/external_services/src/no_encryption/core.rs | //! No encryption core functionalities
/// No encryption type
#[derive(Debug, Clone)]
pub struct NoEncryption;
impl NoEncryption {
/// Encryption functionality
pub fn encrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
data.as_ref().into()
}
/// Decryption functionality
pub fn decrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
data.as_ref().into()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/external_services/src/no_encryption/implementers.rs | crates/external_services/src/no_encryption/implementers.rs | //! Trait implementations for No encryption client
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::{
encryption_interface::{EncryptionError, EncryptionManagementInterface},
secrets_interface::{SecretManagementInterface, SecretsManagementError},
};
use masking::{ExposeInterface, Secret};
use crate::no_encryption::core::NoEncryption;
#[async_trait::async_trait]
impl EncryptionManagementInterface for NoEncryption {
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
Ok(self.encrypt(input))
}
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
Ok(self.decrypt(input))
}
}
#[async_trait::async_trait]
impl SecretManagementInterface for NoEncryption {
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
String::from_utf8(self.decrypt(input.expose()))
.map(Into::into)
.change_context(SecretsManagementError::FetchSecretFailed)
.attach_printable("Failed to convert decrypted value to UTF-8")
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/lib.rs | crates/subscriptions/src/lib.rs | //! Subscription management crate for Hyperswitch
//!
//! This crate provides functionality for managing subscriptions, including:
//! - Subscription creation and management
//! - Invoice handling
//! - Billing processor integration
//! - Payment processing for subscriptions
#[cfg(feature = "v1")]
pub mod core;
pub mod helpers;
pub mod state;
pub mod types;
#[cfg(feature = "v1")]
pub mod workflows;
pub mod webhooks;
pub use core::*;
pub use types::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/helpers.rs | crates/subscriptions/src/helpers.rs | pub use hyperswitch_domain_models::errors::api_error_response;
pub const X_PROFILE_ID: &str = "X-Profile-Id";
pub const X_TENANT_ID: &str = "x-tenant-id";
pub const X_MERCHANT_ID: &str = "X-Merchant-Id";
pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key";
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>;
}
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/subscriptions/src/state.rs | crates/subscriptions/src/state.rs | use common_utils::types::keymanager;
use hyperswitch_domain_models::{
business_profile, configs as domain_configs, customer, invoice as invoice_domain, master_key,
merchant_account, merchant_connector_account, merchant_key_store,
subscription as subscription_domain,
};
use hyperswitch_interfaces::configs;
use router_env::RequestId;
use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore};
#[async_trait::async_trait]
pub trait SubscriptionStorageInterface:
Send
+ Sync
+ std::any::Any
+ dyn_clone::DynClone
+ master_key::MasterKeyInterface
+ scheduler::SchedulerInterface
+ subscription_domain::SubscriptionInterface<Error = errors::StorageError>
+ invoice_domain::InvoiceInterface<Error = errors::StorageError>
+ business_profile::ProfileInterface<Error = errors::StorageError>
+ domain_configs::ConfigInterface<Error = errors::StorageError>
+ customer::CustomerInterface<Error = errors::StorageError>
+ merchant_account::MerchantAccountInterface<Error = errors::StorageError>
+ merchant_key_store::MerchantKeyStoreInterface<Error = errors::StorageError>
+ merchant_connector_account::MerchantConnectorAccountInterface<Error = errors::StorageError>
+ 'static
{
}
dyn_clone::clone_trait_object!(SubscriptionStorageInterface);
#[async_trait::async_trait]
impl SubscriptionStorageInterface for MockDb {}
#[async_trait::async_trait]
impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for RouterStore<T> where
Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface
{
}
#[async_trait::async_trait]
impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for KVRouterStore<T> where
Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface
{
}
pub struct SubscriptionState {
pub store: Box<dyn SubscriptionStorageInterface>,
pub key_store: Option<merchant_key_store::MerchantKeyStore>,
pub key_manager_state: keymanager::KeyManagerState,
pub api_client: Box<dyn hyperswitch_interfaces::api_client::ApiClient>,
pub conf: SubscriptionConfig,
pub tenant: configs::Tenant,
pub event_handler: Box<dyn hyperswitch_interfaces::events::EventHandlerInterface>,
pub connector_converter: Box<dyn hyperswitch_interfaces::api_client::ConnectorConverter>,
}
#[derive(Clone)]
pub struct SubscriptionConfig {
pub proxy: hyperswitch_interfaces::types::Proxy,
pub internal_merchant_id_profile_id_auth: configs::InternalMerchantIdProfileIdAuthSettings,
pub internal_services: configs::InternalServicesConfig,
pub connectors: configs::Connectors,
pub application_source: common_enums::ApplicationSource,
}
impl From<&SubscriptionState> for keymanager::KeyManagerState {
fn from(state: &SubscriptionState) -> Self {
state.key_manager_state.clone()
}
}
impl hyperswitch_interfaces::api_client::ApiClientWrapper for SubscriptionState {
fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy {
self.conf.proxy.clone()
}
fn get_api_client(&self) -> &dyn hyperswitch_interfaces::api_client::ApiClient {
self.api_client.as_ref()
}
fn get_request_id(&self) -> Option<RequestId> {
self.api_client.get_request_id()
}
fn get_request_id_str(&self) -> Option<String> {
self.api_client
.get_request_id()
.map(|req_id| req_id.to_string())
}
fn get_tenant(&self) -> configs::Tenant {
self.tenant.clone()
}
fn get_connectors(&self) -> configs::Connectors {
self.conf.connectors.clone()
}
fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface {
self.event_handler.as_ref()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/core.rs | crates/subscriptions/src/core.rs | use api_models::subscription::{self as subscription_types, SubscriptionResponse};
use common_enums::connector_enums;
use common_utils::id_type::GenerateId;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse, invoice::InvoiceUpdateRequest, platform::Platform,
subscription::SubscriptionUpdate,
};
pub type RouterResponse<T> =
Result<ApplicationResponse<T>, error_stack::Report<errors::ApiErrorResponse>>;
use api_models::enums::SubscriptionStatus;
use crate::{
core::{
billing_processor_handler::BillingHandler,
invoice_handler::InvoiceHandler,
subscription_handler::{SubscriptionHandler, SubscriptionWithHandler},
},
state::SubscriptionState as SessionState,
};
pub mod billing_processor_handler;
pub mod errors;
pub mod invoice_handler;
pub mod payments_api_client;
pub mod subscription_handler;
pub const SUBSCRIPTIONS_MAX_LIST_COUNT: i64 = 10;
pub async fn create_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
request: subscription_types::CreateSubscriptionRequest,
) -> RouterResponse<SubscriptionResponse> {
let subscription_id = common_utils::id_type::SubscriptionId::generate();
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let _customer = SubscriptionHandler::find_customer(&state, &platform, &request.customer_id)
.await
.attach_printable("subscriptions: failed to find customer")?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
profile.clone(),
)
.await?;
let subscription_handler = SubscriptionHandler::new(&state, &platform);
let mut subscription = subscription_handler
.create_subscription_entry(
subscription_id,
&request.customer_id,
billing_handler.connector_name,
billing_handler.merchant_connector_id.clone(),
request.merchant_reference_id.clone(),
&profile.clone(),
request.plan_id.clone(),
Some(request.item_price_id.clone()),
)
.await
.attach_printable("subscriptions: failed to create subscription entry")?;
let estimate_request = subscription_types::EstimateSubscriptionQuery {
plan_id: request.plan_id.clone(),
item_price_id: request.item_price_id.clone(),
coupon_code: None,
};
let estimate = billing_handler
.get_subscription_estimate(&state, estimate_request)
.await?;
let invoice_handler = subscription.get_invoice_handler(profile.clone());
let payment = invoice_handler
.create_payment_with_confirm_false(
subscription.handler.state,
&request,
estimate.total,
estimate.currency,
)
.await
.attach_printable("subscriptions: failed to create payment")?;
let invoice = invoice_handler
.create_invoice_entry(
&state,
billing_handler.merchant_connector_id,
Some(payment.payment_id.clone()),
estimate.total,
estimate.currency,
connector_enums::InvoiceStatus::InvoiceCreated,
billing_handler.connector_name,
None,
None,
)
.await
.attach_printable("subscriptions: failed to create invoice")?;
subscription
.update_subscription(SubscriptionUpdate::new(
None,
payment.payment_method_id.clone(),
None,
request.plan_id,
Some(request.item_price_id),
))
.await
.attach_printable("subscriptions: failed to update subscription")?;
let response = SubscriptionWithHandler::to_subscription_response(
&subscription.subscription,
Some(payment),
Some(&invoice),
)?;
Ok(ApplicationResponse::Json(response))
}
pub async fn get_subscription_items(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
query: subscription_types::GetSubscriptionItemsQuery,
) -> RouterResponse<Vec<subscription_types::GetSubscriptionItemsResponse>> {
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let subscription_handler = SubscriptionHandler::new(&state, &platform);
if let Some(client_secret) = query.client_secret {
subscription_handler
.find_and_validate_subscription(&client_secret.into())
.await?
};
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
profile.clone(),
)
.await?;
let get_items_response = billing_handler
.get_subscription_items(&state, query.limit, query.offset, query.item_type)
.await?;
let mut response = Vec::new();
for item in &get_items_response.list {
let item_price_response = billing_handler
.get_subscription_item_prices(&state, item.subscription_provider_item_id.clone())
.await?;
response.push(subscription_types::GetSubscriptionItemsResponse {
item_id: item.subscription_provider_item_id.clone(),
name: item.name.clone(),
description: item.description.clone(),
price_id: item_price_response
.list
.into_iter()
.map(subscription_types::SubscriptionItemPrices::from)
.collect::<Vec<_>>(),
});
}
Ok(ApplicationResponse::Json(response))
}
/// Creates and confirms a subscription in one operation.
pub async fn create_and_confirm_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
request: subscription_types::CreateAndConfirmSubscriptionRequest,
) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> {
request
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData {
message: message.to_string(),
})?;
let subscription_id = common_utils::id_type::SubscriptionId::generate();
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let customer = SubscriptionHandler::find_customer(&state, &platform, &request.customer_id)
.await
.attach_printable("subscriptions: failed to find customer")?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
profile.clone(),
)
.await?;
let subscription_handler = SubscriptionHandler::new(&state, &platform);
let mut subs_handler = subscription_handler
.create_subscription_entry(
subscription_id.clone(),
&request.customer_id,
billing_handler.connector_name,
billing_handler.merchant_connector_id.clone(),
request.merchant_reference_id.clone(),
&profile.clone(),
request.plan_id.clone(),
Some(request.item_price_id.clone()),
)
.await
.attach_printable("subscriptions: failed to create subscription entry")?;
let invoice_handler = subs_handler.get_invoice_handler(profile.clone());
let customer_create_response = billing_handler
.create_customer_on_connector(
&state,
customer.clone(),
request.customer_id.clone(),
request.get_billing_address(),
request
.payment_details
.payment_method_data
.clone()
.and_then(|data| data.payment_method_data),
)
.await?;
let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer(
&state,
&platform,
&billing_handler.merchant_connector_id,
&customer,
customer_create_response,
)
.await
.attach_printable("Failed to update customer with connector customer ID")?;
let subscription_create_response = billing_handler
.create_subscription_on_connector(
&state,
subs_handler.subscription.clone(),
Some(request.item_price_id.clone()),
request.get_billing_address(),
)
.await?;
let invoice_details = subscription_create_response.invoice_details;
let (amount, currency) =
InvoiceHandler::get_amount_and_currency((None, None), invoice_details.clone());
let payment_response = invoice_handler
.create_and_confirm_payment(&state, &request, amount, currency)
.await?;
let invoice_entry = invoice_handler
.create_invoice_entry(
&state,
profile.get_billing_processor_id()?,
Some(payment_response.payment_id.clone()),
amount,
currency,
invoice_details
.clone()
.and_then(|invoice| invoice.status)
.unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated),
billing_handler.connector_name,
None,
invoice_details.clone().map(|invoice| invoice.id),
)
.await?;
invoice_handler
.create_invoice_sync_job(
&state,
&invoice_entry,
invoice_details.clone().map(|details| details.id),
billing_handler.connector_name,
)
.await?;
subs_handler
.update_subscription(SubscriptionUpdate::new(
Some(
subscription_create_response
.subscription_id
.get_string_repr()
.to_string(),
),
payment_response.payment_method_id.clone(),
Some(SubscriptionStatus::from(subscription_create_response.status).to_string()),
request.plan_id,
Some(request.item_price_id),
))
.await?;
let response = subs_handler.generate_response(
&invoice_entry,
&payment_response,
subscription_create_response.status,
)?;
Ok(ApplicationResponse::Json(response))
}
pub async fn confirm_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
request: subscription_types::ConfirmSubscriptionRequest,
subscription_id: common_utils::id_type::SubscriptionId,
) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> {
// Validate request
request
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData {
message: message.to_string(),
})?;
// Find the subscription from database
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let handler = SubscriptionHandler::new(&state, &platform);
if let Some(client_secret) = request.client_secret.clone() {
handler
.find_and_validate_subscription(&client_secret.into())
.await?
};
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let invoice_handler = subscription_entry.get_invoice_handler(profile.clone());
let invoice = invoice_handler
.get_latest_invoice(&state)
.await
.attach_printable("subscriptions: failed to get latest invoice")?;
let payment_response = invoice_handler
.confirm_payment(
&state,
invoice
.payment_intent_id
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_intent_id",
})?,
&request,
)
.await?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
profile.clone(),
)
.await?;
let customer = SubscriptionHandler::find_customer(
&state,
&platform,
&subscription_entry.subscription.customer_id,
)
.await
.attach_printable("subscriptions: failed to find customer")?;
let invoice_handler = subscription_entry.get_invoice_handler(profile);
let subscription = subscription_entry.subscription.clone();
let customer_create_response = billing_handler
.create_customer_on_connector(
&state,
customer.clone(),
subscription.customer_id.clone(),
payment_response.get_billing_address(),
request
.payment_details
.payment_method_data
.as_ref()
.and_then(|data| data.payment_method_data.clone()),
)
.await?;
let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer(
&state,
&platform,
&billing_handler.merchant_connector_id,
&customer,
customer_create_response,
)
.await
.attach_printable("Failed to update customer with connector customer ID")?;
let subscription_create_response = billing_handler
.create_subscription_on_connector(
&state,
subscription.clone(),
subscription.item_price_id.clone(),
payment_response.get_billing_address(),
)
.await?;
let invoice_details = subscription_create_response.invoice_details;
let update_request = InvoiceUpdateRequest::update_payment_and_status(
payment_response.payment_method_id.clone(),
Some(payment_response.payment_id.clone()),
invoice_details
.clone()
.and_then(|invoice| invoice.status)
.unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated),
invoice_details.clone().map(|invoice| invoice.id),
);
let invoice_entry = invoice_handler
.update_invoice(&state, invoice.id, update_request)
.await?;
invoice_handler
.create_invoice_sync_job(
&state,
&invoice_entry,
invoice_details.map(|invoice| invoice.id),
billing_handler.connector_name,
)
.await?;
subscription_entry
.update_subscription(SubscriptionUpdate::new(
Some(
subscription_create_response
.subscription_id
.get_string_repr()
.to_string(),
),
payment_response.payment_method_id.clone(),
Some(SubscriptionStatus::from(subscription_create_response.status).to_string()),
subscription.plan_id.clone(),
subscription.item_price_id.clone(),
))
.await?;
let response = subscription_entry.generate_response(
&invoice_entry,
&payment_response,
subscription_create_response.status,
)?;
Ok(ApplicationResponse::Json(response))
}
pub async fn get_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
subscription_id: common_utils::id_type::SubscriptionId,
) -> RouterResponse<SubscriptionResponse> {
let _profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile in get_subscription")?;
let handler = SubscriptionHandler::new(&state, &platform);
let subscription = handler
.find_subscription(subscription_id)
.await
.attach_printable("subscriptions: failed to get subscription entry in get_subscription")?;
let response =
SubscriptionWithHandler::to_subscription_response(&subscription.subscription, None, None)?;
Ok(ApplicationResponse::Json(response))
}
pub async fn get_estimate(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
query: subscription_types::EstimateSubscriptionQuery,
) -> RouterResponse<subscription_types::EstimateSubscriptionResponse> {
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile in get_estimate")?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
profile,
)
.await?;
let estimate = billing_handler
.get_subscription_estimate(&state, query)
.await?;
Ok(ApplicationResponse::Json(estimate.into()))
}
pub async fn pause_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
subscription_id: common_utils::id_type::SubscriptionId,
request: subscription_types::PauseSubscriptionRequest,
) -> RouterResponse<subscription_types::PauseSubscriptionResponse> {
let _profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile in pause_subscription")?;
let handler = SubscriptionHandler::new(&state, &platform);
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
_profile.clone(),
)
.await?;
// Call the billing processor to pause the subscription
let pause_response = billing_handler
.pause_subscription_on_connector(&state, &subscription_entry.subscription, &request)
.await?;
let status = SubscriptionStatus::from(pause_response.status);
// Update the subscription status in our database
subscription_entry
.update_subscription(SubscriptionUpdate::update_status(status.to_string()))
.await?;
let response = subscription_types::PauseSubscriptionResponse {
id: subscription_entry.subscription.id.clone(),
status,
merchant_reference_id: subscription_entry
.subscription
.merchant_reference_id
.clone(),
profile_id: subscription_entry.subscription.profile_id.clone(),
merchant_id: subscription_entry.subscription.merchant_id.clone(),
customer_id: subscription_entry.subscription.customer_id.clone(),
paused_at: pause_response.paused_at,
};
Ok(ApplicationResponse::Json(response))
}
pub async fn resume_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
subscription_id: common_utils::id_type::SubscriptionId,
request: subscription_types::ResumeSubscriptionRequest,
) -> RouterResponse<subscription_types::ResumeSubscriptionResponse> {
let _profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable(
"subscriptions: failed to find business profile in resume_subscription",
)?;
let handler = SubscriptionHandler::new(&state, &platform);
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
_profile.clone(),
)
.await?;
// Call the billing processor to resume the subscription
let resume_response = billing_handler
.resume_subscription_on_connector(&state, &subscription_entry.subscription, &request)
.await?;
let status = SubscriptionStatus::from(resume_response.status);
// Update the subscription status in our database
subscription_entry
.update_subscription(SubscriptionUpdate::update_status(status.to_string()))
.await?;
let response = subscription_types::ResumeSubscriptionResponse {
id: subscription_entry.subscription.id.clone(),
status,
merchant_reference_id: subscription_entry
.subscription
.merchant_reference_id
.clone(),
profile_id: subscription_entry.subscription.profile_id.clone(),
merchant_id: subscription_entry.subscription.merchant_id.clone(),
customer_id: subscription_entry.subscription.customer_id.clone(),
next_billing_at: resume_response.next_billing_at,
};
Ok(ApplicationResponse::Json(response))
}
pub async fn cancel_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
subscription_id: common_utils::id_type::SubscriptionId,
request: subscription_types::CancelSubscriptionRequest,
) -> RouterResponse<subscription_types::CancelSubscriptionResponse> {
let _profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable(
"subscriptions: failed to find business profile in cancel_subscription",
)?;
let handler = SubscriptionHandler::new(&state, &platform);
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
_profile.clone(),
)
.await?;
// Call the billing processor to cancel the subscription
let cancel_response = billing_handler
.cancel_subscription_on_connector(&state, &subscription_entry.subscription, &request)
.await?;
let status = SubscriptionStatus::from(cancel_response.status);
// Update the subscription status in our database
subscription_entry
.update_subscription(SubscriptionUpdate::update_status(status.to_string()))
.await?;
let response = subscription_types::CancelSubscriptionResponse {
id: subscription_entry.subscription.id.clone(),
status,
merchant_reference_id: subscription_entry
.subscription
.merchant_reference_id
.clone(),
profile_id: subscription_entry.subscription.profile_id.clone(),
merchant_id: subscription_entry.subscription.merchant_id.clone(),
customer_id: subscription_entry.subscription.customer_id.clone(),
cancelled_at: cancel_response.cancelled_at,
};
Ok(ApplicationResponse::Json(response))
}
pub async fn update_subscription(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
subscription_id: common_utils::id_type::SubscriptionId,
request: subscription_types::UpdateSubscriptionRequest,
) -> RouterResponse<SubscriptionResponse> {
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile in get_subscription")?;
let handler = SubscriptionHandler::new(&state, &platform);
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let invoice_handler = subscription_entry.get_invoice_handler(profile.clone());
let invoice = invoice_handler
.get_latest_invoice(&state)
.await
.attach_printable("subscriptions: failed to get latest invoice")?;
let subscription = subscription_entry.subscription.clone();
subscription_entry
.update_subscription(SubscriptionUpdate::new(
None,
None,
None,
Some(request.plan_id.clone()),
Some(request.item_price_id.clone()),
))
.await?;
let billing_handler = BillingHandler::create(
&state,
platform.get_processor().get_account(),
platform.get_processor().get_key_store(),
profile.clone(),
)
.await?;
let estimate_request = subscription_types::EstimateSubscriptionQuery {
plan_id: Some(request.plan_id.clone()),
item_price_id: request.item_price_id.clone(),
coupon_code: None,
};
let estimate = billing_handler
.get_subscription_estimate(&state, estimate_request)
.await?;
let update_request = InvoiceUpdateRequest::update_amount_and_currency(
estimate.total,
estimate.currency.to_string(),
);
let invoice_entry = invoice_handler
.update_invoice(&state, invoice.id, update_request)
.await?;
let _payment_response = invoice_handler
.update_payment(
&state,
estimate.total,
estimate.currency,
invoice_entry.payment_intent_id.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_intent_id",
},
)?,
)
.await?;
Box::pin(get_subscription(
state,
platform,
profile_id,
subscription.id,
))
.await
}
pub async fn list_subscriptions(
state: SessionState,
platform: Platform,
profile_id: common_utils::id_type::ProfileId,
query: subscription_types::ListSubscriptionQuery,
) -> RouterResponse<Vec<SubscriptionResponse>> {
SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile in list_subscriptions")?;
let handler = SubscriptionHandler::new(&state, &platform);
let subscriptions = handler
.list_subscriptions_by_profile_id(
&profile_id,
Some(query.limit.unwrap_or(SUBSCRIPTIONS_MAX_LIST_COUNT)),
Some(query.offset.unwrap_or_default()),
)
.await
.attach_printable("subscriptions: failed to list subscriptions by profile id")?;
let mut subscriptions_resonse = Vec::new();
for subscription in subscriptions {
let response = SubscriptionWithHandler::to_subscription_response(&subscription, None, None)
.attach_printable("subscriptions: failed to convert subscription entry to response")?;
subscriptions_resonse.push(response);
}
Ok(ApplicationResponse::Json(subscriptions_resonse))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/workflows.rs | crates/subscriptions/src/workflows.rs | //! Workflows module for subscription functionality
//!
//! This module contains workflow definitions for subscription-related operations
pub mod invoice_sync;
// Re-export workflow types for easier access
pub use invoice_sync::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/webhooks.rs | crates/subscriptions/src/webhooks.rs | use std::str::FromStr;
use api_models::webhooks::WebhookResponseTracker;
use common_enums::{connector_enums::Connector, InvoiceStatus};
use common_utils::{consts, errors::CustomResult, generate_id};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
business_profile, errors::api_error_response as errors, invoice, merchant_connector_account,
platform,
};
use hyperswitch_interfaces::{
api::ConnectorCommon, connector_integration_interface, errors::ConnectorError,
webhooks::IncomingWebhook,
};
use router_env::{instrument, logger, tracing};
use crate::state::SubscriptionState as SessionState;
#[cfg(feature = "v1")]
use crate::subscription_handler::SubscriptionHandler;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn incoming_webhook_flow(
state: SessionState,
platform: platform::Platform,
business_profile: business_profile::Profile,
_webhook_details: api_models::webhooks::IncomingWebhookDetails,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: api_models::webhooks::IncomingWebhookEvent,
merchant_connector_account: merchant_connector_account::MerchantConnectorAccount,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let billing_connector_mca_id = merchant_connector_account.merchant_connector_id.clone();
// Only process invoice_generated events for MIT payments
if event_type != api_models::webhooks::IncomingWebhookEvent::InvoiceGenerated {
return Ok(WebhookResponseTracker::NoEffect);
}
if !source_verified {
logger::error!("Webhook source verification failed for subscription webhook flow");
return Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
));
}
let connector_name = connector_enum.id().to_string();
let connector = Connector::from_str(&connector_name)
.change_context(ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name}"))?;
let mit_payment_data = connector_enum
.get_subscription_mit_payment_data(request_details)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to extract MIT payment data from subscription webhook")?;
let profile_id = business_profile.get_id().clone();
let profile = SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile in get_subscription")?;
let handler = SubscriptionHandler::new(&state, &platform);
let subscription_id = mit_payment_data.subscription_id.clone();
let subscription_with_handler = handler
.find_subscription(subscription_id.clone())
.await
.attach_printable("subscriptions: failed to get subscription entry in get_subscription")?;
let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone());
let invoice = invoice_handler
.find_invoice_by_subscription_id_connector_invoice_id(
&state,
subscription_id,
mit_payment_data.invoice_id.clone(),
)
.await
.attach_printable(
"subscriptions: failed to get invoice by subscription id and connector invoice id",
)?;
if let Some(invoice) = invoice {
// During CIT payment we would have already created invoice entry with status as PaymentPending or Paid.
// So we skip incoming webhook for the already processed invoice
if invoice.status != InvoiceStatus::InvoiceCreated {
logger::info!("Invoice is already being processed, skipping MIT payment creation");
return Ok(WebhookResponseTracker::NoEffect);
}
}
let payment_method_id = subscription_with_handler
.subscription
.payment_method_id
.clone()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "No payment method found for subscription".to_string(),
})
.attach_printable("No payment method found for subscription")?;
logger::info!("Payment method ID found: {}", payment_method_id);
let payment_id = generate_id(consts::ID_LENGTH, "pay");
let payment_id = common_utils::id_type::PaymentId::wrap(payment_id).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_id",
},
)?;
// Multiple MIT payments for the same invoice_generated event is avoided by having the unique constraint on (subscription_id, connector_invoice_id) in the invoices table
let invoice_entry = invoice_handler
.create_invoice_entry(
&state,
billing_connector_mca_id.clone(),
Some(payment_id),
mit_payment_data.amount_due,
mit_payment_data.currency_code,
InvoiceStatus::PaymentPending,
connector,
None,
Some(mit_payment_data.invoice_id.clone()),
)
.await?;
// Create a sync job for the invoice with generated payment_id before initiating MIT payment creation.
// This ensures that if payment creation call fails, the sync job can still retrieve the payment status
invoice_handler
.create_invoice_sync_job(
&state,
&invoice_entry,
Some(mit_payment_data.invoice_id.clone()),
connector,
)
.await?;
let payment_response = invoice_handler
.create_mit_payment(
&state,
mit_payment_data.amount_due,
mit_payment_data.currency_code,
&payment_method_id.clone(),
)
.await?;
let update_request = invoice::InvoiceUpdateRequest::update_payment_and_status(
payment_response.payment_method_id,
Some(payment_response.payment_id.clone()),
InvoiceStatus::from(payment_response.status),
Some(mit_payment_data.invoice_id.clone()),
);
let _updated_invoice = invoice_handler
.update_invoice(&state, invoice_entry.id.clone(), update_request)
.await?;
Ok(WebhookResponseTracker::NoEffect)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/types.rs | crates/subscriptions/src/types.rs | //! Types module for subscription functionality
//!
//! This module contains type definitions and storage types for subscriptions
pub mod storage;
// Re-export subscription types from api_models for convenience
pub use api_models::subscription as subscription_types;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/workflows/invoice_sync.rs | crates/subscriptions/src/workflows/invoice_sync.rs | use std::str::FromStr;
#[cfg(feature = "v1")]
use api_models::subscription as subscription_types;
use common_utils::{errors::CustomResult, ext_traits::StringExt};
use error_stack::ResultExt;
use hyperswitch_domain_models::{self as domain, invoice::InvoiceUpdateRequest};
use router_env::logger;
use scheduler::{
errors,
types::process_data,
utils as scheduler_utils,
workflows::storage::{business_status, ProcessTracker, ProcessTrackerNew},
};
use storage_impl::StorageError;
use crate::{
core::{
billing_processor_handler as billing, errors as router_errors, invoice_handler,
payments_api_client,
},
helpers::ForeignTryFrom,
state::{SubscriptionState as SessionState, SubscriptionStorageInterface as StorageInterface},
types::storage,
};
const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC";
const INVOICE_SYNC_WORKFLOW_TAG: &str = "INVOICE";
pub struct InvoiceSyncHandler<'a> {
pub state: &'a SessionState,
pub tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
pub key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount,
pub customer: hyperswitch_domain_models::customer::Customer,
pub profile: hyperswitch_domain_models::business_profile::Profile,
pub subscription: hyperswitch_domain_models::subscription::Subscription,
pub invoice: hyperswitch_domain_models::invoice::Invoice,
}
#[cfg(feature = "v1")]
impl<'a> InvoiceSyncHandler<'a> {
pub async fn create(
state: &'a SessionState,
tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
) -> Result<Self, errors::ProcessTrackerError> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&tracking_data.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.attach_printable("Failed to fetch Merchant key store from DB")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
.await
.attach_printable("Subscriptions: Failed to fetch Merchant Account from DB")?;
let profile = state
.store
.find_business_profile_by_profile_id(&key_store, &tracking_data.profile_id)
.await
.attach_printable("Subscriptions: Failed to fetch Business Profile from DB")?;
let customer = state
.store
.find_customer_by_customer_id_merchant_id(
&tracking_data.customer_id,
merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
.await
.attach_printable("Subscriptions: Failed to fetch Customer from DB")?;
let subscription = state
.store
.find_by_merchant_id_subscription_id(
&key_store,
merchant_account.get_id(),
tracking_data.subscription_id.get_string_repr().to_string(),
)
.await
.attach_printable("Subscriptions: Failed to fetch subscription from DB")?;
let invoice = state
.store
.find_invoice_by_invoice_id(
&key_store,
tracking_data.invoice_id.get_string_repr().to_string(),
)
.await
.attach_printable("invoices: unable to get latest invoice from database")?;
Ok(Self {
state,
tracking_data,
key_store,
merchant_account,
customer,
profile,
subscription,
invoice,
})
}
async fn finish_process_with_business_status(
&self,
process: &ProcessTracker,
business_status: &'static str,
) -> CustomResult<(), router_errors::ApiErrorResponse> {
self.state
.store
.as_scheduler()
.finish_process_with_business_status(process.clone(), business_status)
.await
.change_context(router_errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update process tracker status")
}
pub async fn perform_payments_sync(
state: &SessionState,
payment_intent_id: Option<&common_utils::id_type::PaymentId>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<subscription_types::PaymentResponseData, router_errors::ApiErrorResponse>
{
let payment_id =
payment_intent_id.ok_or(router_errors::ApiErrorResponse::SubscriptionError {
operation: "Invoice_sync: Missing Payment Intent ID in Invoice".to_string(),
})?;
let payments_response = payments_api_client::PaymentsApiClient::sync_payment(
state,
payment_id.get_string_repr().to_string(),
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
.await
.change_context(router_errors::ApiErrorResponse::SubscriptionError {
operation: "Invoice_sync: Failed to sync payment status from payments microservice"
.to_string(),
})
.attach_printable("Failed to sync payment status from payments microservice")?;
Ok(payments_response)
}
pub fn generate_response(
subscription: &hyperswitch_domain_models::subscription::Subscription,
invoice: &hyperswitch_domain_models::invoice::Invoice,
payment_response: &subscription_types::PaymentResponseData,
) -> CustomResult<
subscription_types::ConfirmSubscriptionResponse,
router_errors::ApiErrorResponse,
> {
subscription_types::ConfirmSubscriptionResponse::foreign_try_from((
subscription,
invoice,
payment_response,
))
}
pub async fn form_response_for_retry_outgoing_webhook_task(
state: SessionState,
key_store: &domain::merchant_key_store::MerchantKeyStore,
invoice_id: String,
profile_id: &common_utils::id_type::ProfileId,
merchant_account: &domain::merchant_account::MerchantAccount,
) -> Result<subscription_types::ConfirmSubscriptionResponse, errors::ProcessTrackerError> {
let invoice = state
.store
.find_invoice_by_invoice_id(key_store, invoice_id.clone())
.await
.map_err(|err| {
logger::error!(
?err,
"invoices: unable to get latest invoice with id {invoice_id} from database"
);
errors::ProcessTrackerError::ResourceFetchingFailed {
resource_name: "Invoice".to_string(),
}
})?;
let subscription = state
.store
.find_by_merchant_id_subscription_id(
key_store,
merchant_account.get_id(),
invoice.subscription_id.get_string_repr().to_string(),
)
.await
.map_err(|err| {
logger::error!(
?err,
"subscription: unable to get subscription from database"
);
errors::ProcessTrackerError::ResourceFetchingFailed {
resource_name: "Subscription".to_string(),
}
})?;
let payments_response = InvoiceSyncHandler::perform_payments_sync(
&state,
invoice.payment_intent_id.as_ref(),
profile_id,
merchant_account.get_id(),
)
.await
.map_err(|err| {
logger::error!(
?err,
"subscription: unable to make PSync Call to payments microservice"
);
errors::ProcessTrackerError::EApiErrorResponse
})?;
let response = Self::generate_response(&subscription, &invoice, &payments_response)
.map_err(|err| {
logger::error!(
?err,
"subscription: unable to form ConfirmSubscriptionResponse from foreign types"
);
errors::ProcessTrackerError::DeserializationFailed
})?;
Ok(response)
}
pub async fn perform_billing_processor_record_back_if_possible(
&self,
payment_response: subscription_types::PaymentResponseData,
payment_status: common_enums::AttemptStatus,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus,
) -> CustomResult<hyperswitch_domain_models::invoice::Invoice, router_errors::ApiErrorResponse>
{
if let Some(connector_invoice_id) = connector_invoice_id {
Box::pin(self.perform_billing_processor_record_back(
payment_response,
payment_status,
connector_invoice_id,
invoice_sync_status,
))
.await
.attach_printable("Failed to record back to billing processor")
} else {
Ok(self.invoice.clone())
}
}
pub async fn perform_billing_processor_record_back(
&self,
payment_response: subscription_types::PaymentResponseData,
payment_status: common_enums::AttemptStatus,
connector_invoice_id: common_utils::id_type::InvoiceId,
invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus,
) -> CustomResult<hyperswitch_domain_models::invoice::Invoice, router_errors::ApiErrorResponse>
{
logger::info!("perform_billing_processor_record_back");
let billing_handler = billing::BillingHandler::create(
self.state,
&self.merchant_account,
&self.key_store,
self.profile.clone(),
)
.await
.attach_printable("Failed to create billing handler")?;
let invoice_handler = invoice_handler::InvoiceHandler::new(
self.subscription.clone(),
self.merchant_account.clone(),
self.profile.clone(),
self.key_store.clone(),
);
// TODO: Handle retries here on failure
billing_handler
.record_back_to_billing_processor(
self.state,
connector_invoice_id.clone(),
payment_response.payment_id.to_owned(),
payment_status,
payment_response.amount,
payment_response.currency,
payment_response.payment_method_type,
)
.await
.attach_printable("Failed to record back to billing processor")?;
let update_request = InvoiceUpdateRequest::update_connector_and_status(
connector_invoice_id,
common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status),
);
invoice_handler
.update_invoice(self.state, self.invoice.id.to_owned(), update_request)
.await
.attach_printable("Failed to update invoice in DB")
}
pub async fn transition_workflow_state(
&self,
process: ProcessTracker,
payment_response: subscription_types::PaymentResponseData,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> CustomResult<hyperswitch_domain_models::invoice::Invoice, router_errors::ApiErrorResponse>
{
logger::info!(
"transition_workflow_state called with status: {:?}",
payment_response.status
);
let invoice_sync_status =
storage::invoice_sync::InvoiceSyncPaymentStatus::from(payment_response.status);
let (payment_status, status) = match invoice_sync_status {
storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentSucceeded => (common_enums::AttemptStatus::Charged, "succeeded"),
storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentFailed => (common_enums::AttemptStatus::Failure, "failed"),
storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentProcessing => return Err(
router_errors::ApiErrorResponse::SubscriptionError {
operation: "Invoice_sync: Payment in processing state, cannot transition workflow state"
.to_string(),
},
)?,
};
logger::info!("Performing billing processor record back for status: {status}");
let invoice = Box::pin(self.perform_billing_processor_record_back_if_possible(
payment_response.clone(),
payment_status,
connector_invoice_id,
invoice_sync_status.clone(),
))
.await
.attach_printable(format!(
"Failed to record back {status} status to billing processor"
))?;
self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT)
.await
.change_context(router_errors::ApiErrorResponse::SubscriptionError {
operation: "Invoice_sync process_tracker task completion".to_string(),
})
.attach_printable("Failed to update process tracker status")?;
Ok(invoice)
}
}
#[cfg(feature = "v1")]
pub async fn perform_subscription_invoice_sync(
state: &SessionState,
process: ProcessTracker,
tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
) -> Result<
(
InvoiceSyncHandler<'_>,
subscription_types::PaymentResponseData,
),
errors::ProcessTrackerError,
> {
let mut handler = InvoiceSyncHandler::create(state, tracking_data).await?;
let payments_response = InvoiceSyncHandler::perform_payments_sync(
handler.state,
handler.invoice.payment_intent_id.as_ref(),
handler.profile.get_id(),
handler.merchant_account.get_id(),
)
.await?;
match Box::pin(handler.transition_workflow_state(
process.clone(),
payments_response.clone(),
handler.tracking_data.connector_invoice_id.clone(),
))
.await
{
Err(e) => {
logger::error!(?e, "Error in transitioning workflow state");
retry_subscription_invoice_sync_task(
&*handler.state.store,
handler.tracking_data.connector_name.to_string().clone(),
handler.merchant_account.get_id().to_owned(),
process,
)
.await
.change_context(router_errors::ApiErrorResponse::SubscriptionError {
operation: "Invoice_sync process_tracker task retry".to_string(),
})
.attach_printable("Failed to update process tracker status")?;
}
Ok(invoice) => {
handler.invoice = invoice.clone();
}
}
Ok((handler, payments_response))
}
pub async fn create_invoice_sync_job(
state: &SessionState,
request: storage::invoice_sync::InvoiceSyncRequest,
) -> CustomResult<(), router_errors::ApiErrorResponse> {
let tracking_data = storage::invoice_sync::InvoiceSyncTrackingData::from(request);
let process_tracker_entry = ProcessTrackerNew::new(
common_utils::generate_id(common_utils::consts::ID_LENGTH, "proc"),
INVOICE_SYNC_WORKFLOW.to_string(),
common_enums::ProcessTrackerRunner::InvoiceSyncflow,
vec![INVOICE_SYNC_WORKFLOW_TAG.to_string()],
tracking_data,
Some(0),
common_utils::date_time::now(),
common_types::consts::API_VERSION,
state.conf.application_source,
)
.change_context(router_errors::ApiErrorResponse::InternalServerError)
.attach_printable("subscriptions: unable to form process_tracker type")?;
state
.store
.insert_process(process_tracker_entry)
.await
.change_context(router_errors::ApiErrorResponse::InternalServerError)
.attach_printable("subscriptions: unable to insert process_tracker entry in DB")?;
Ok(())
}
pub async fn get_subscription_invoice_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: CustomResult<process_data::SubscriptionInvoiceSyncPTMapping, StorageError> = db
.find_config_by_key(&format!("invoice_sync_pt_mapping_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("SubscriptionInvoiceSyncPTMapping")
.change_context(StorageError::DeserializationFailed)
.attach_printable("Failed to deserialize invoice_sync_pt_mapping config to struct")
});
let mapping = match mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::SubscriptionInvoiceSyncPTMapping::default()
}
};
let time_delta = scheduler_utils::get_subscription_invoice_sync_retry_schedule_time(
mapping,
merchant_id,
retry_count,
);
Ok(scheduler_utils::get_time_from_delta(time_delta))
}
pub async fn retry_subscription_invoice_sync_task(
db: &dyn StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let schedule_time = get_subscription_invoice_sync_process_schedule_time(
db,
connector.as_str(),
&merchant_id,
pt.retry_count + 1,
)
.await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler()
.retry_process(pt, s_time)
.await
.attach_printable("Failed to retry subscription invoice sync task")?;
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await
.attach_printable("Failed to finish subscription invoice sync task")?;
}
}
Ok(())
}
impl
ForeignTryFrom<(
&domain::subscription::Subscription,
&domain::invoice::Invoice,
&subscription_types::PaymentResponseData,
)> for subscription_types::ConfirmSubscriptionResponse
{
type Error = error_stack::Report<router_errors::ApiErrorResponse>;
fn foreign_try_from(
value: (
&domain::subscription::Subscription,
&domain::invoice::Invoice,
&subscription_types::PaymentResponseData,
),
) -> Result<Self, Self::Error> {
let (subscription, invoice, payment_response) = value;
let status = common_enums::SubscriptionStatus::from_str(subscription.status.as_str())
.map_err(|_| router_errors::ApiErrorResponse::SubscriptionError {
operation: "Failed to parse subscription status".to_string(),
})
.attach_printable("Failed to parse subscription status")?;
Ok(Self {
id: subscription.id.clone(),
merchant_reference_id: subscription.merchant_reference_id.clone(),
status,
plan_id: subscription.plan_id.clone(),
profile_id: subscription.profile_id.to_owned(),
payment: Some(payment_response.clone()),
customer_id: Some(subscription.customer_id.clone()),
item_price_id: subscription.item_price_id.clone(),
coupon: None,
billing_processor_subscription_id: subscription.connector_subscription_id.clone(),
invoice: Some(subscription_types::Invoice::foreign_try_from(invoice)?),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.