id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
file_api_models_3067209598787067848
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/external_service_auth.rs // Contains: 3 structs, 1 enums 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, } } }
{ "crate": "api_models", "file": "crates/api_models/src/external_service_auth.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-4639175027979095469
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/verify_connector.rs // Contains: 1 structs, 0 enums use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{admin, enums}; #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyConnectorRequest { pub connector_name: enums::Connector, pub connector_account_details: admin::ConnectorAuthType, } common_utils::impl_api_event_type!(Miscellaneous, (VerifyConnectorRequest));
{ "crate": "api_models", "file": "crates/api_models/src/verify_connector.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_1630640115695368996
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/recon.rs // Contains: 4 structs, 0 enums 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>, }
{ "crate": "api_models", "file": "crates/api_models/src/recon.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_4252609102820975270
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/poll.rs // Contains: 1 structs, 1 enums use common_utils::events::{ApiEventMetric, ApiEventsType}; use serde::Serialize; use utoipa::ToSchema; #[derive(Debug, ToSchema, Clone, Serialize)] pub struct PollResponse { /// The poll id pub poll_id: String, /// Status of the poll pub status: PollStatus, } #[derive(Debug, strum::Display, strum::EnumString, Clone, serde::Serialize, ToSchema)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PollStatus { Pending, Completed, NotFound, } impl ApiEventMetric for PollResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Poll { poll_id: self.poll_id.clone(), }) } }
{ "crate": "api_models", "file": "crates/api_models/src/poll.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_7836978701455006643
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/webhooks.rs // Contains: 2 structs, 9 enums use common_utils::custom_serde; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; #[cfg(feature = "payouts")] use crate::payouts; use crate::{disputes, enums as api_enums, mandates, payments, refunds}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { /// Authorization + Capture failure PaymentIntentFailure, /// Authorization + Capture success PaymentIntentSuccess, PaymentIntentProcessing, PaymentIntentPartiallyFunded, PaymentIntentCancelled, PaymentIntentCancelFailure, PaymentIntentAuthorizationSuccess, PaymentIntentAuthorizationFailure, PaymentIntentExtendAuthorizationSuccess, PaymentIntentExtendAuthorizationFailure, PaymentIntentCaptureSuccess, PaymentIntentCaptureFailure, PaymentIntentExpired, PaymentActionRequired, EventNotSupported, SourceChargeable, SourceTransactionCreated, RefundFailure, RefundSuccess, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, MandateActive, MandateRevoked, EndpointVerification, ExternalAuthenticationARes, FrmApproved, FrmRejected, #[cfg(feature = "payouts")] PayoutSuccess, #[cfg(feature = "payouts")] PayoutFailure, #[cfg(feature = "payouts")] PayoutProcessing, #[cfg(feature = "payouts")] PayoutCancelled, #[cfg(feature = "payouts")] PayoutCreated, #[cfg(feature = "payouts")] PayoutExpired, #[cfg(feature = "payouts")] PayoutReversed, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentFailure, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentSuccess, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentPending, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryInvoiceCancel, SetupWebhook, InvoiceGenerated, } impl IncomingWebhookEvent { /// Convert UCS event type integer to IncomingWebhookEvent /// Maps from proto WebhookEventType enum values to IncomingWebhookEvent variants pub fn from_ucs_event_type(event_type: i32) -> Self { match event_type { 0 => Self::EventNotSupported, // Payment intent events 1 => Self::PaymentIntentFailure, 2 => Self::PaymentIntentSuccess, 3 => Self::PaymentIntentProcessing, 4 => Self::PaymentIntentPartiallyFunded, 5 => Self::PaymentIntentCancelled, 6 => Self::PaymentIntentCancelFailure, 7 => Self::PaymentIntentAuthorizationSuccess, 8 => Self::PaymentIntentAuthorizationFailure, 9 => Self::PaymentIntentCaptureSuccess, 10 => Self::PaymentIntentCaptureFailure, 11 => Self::PaymentIntentExpired, 12 => Self::PaymentActionRequired, // Source events 13 => Self::SourceChargeable, 14 => Self::SourceTransactionCreated, // Refund events 15 => Self::RefundFailure, 16 => Self::RefundSuccess, // Dispute events 17 => Self::DisputeOpened, 18 => Self::DisputeExpired, 19 => Self::DisputeAccepted, 20 => Self::DisputeCancelled, 21 => Self::DisputeChallenged, 22 => Self::DisputeWon, 23 => Self::DisputeLost, // Mandate events 24 => Self::MandateActive, 25 => Self::MandateRevoked, // Miscellaneous events 26 => Self::EndpointVerification, 27 => Self::ExternalAuthenticationARes, 28 => Self::FrmApproved, 29 => Self::FrmRejected, // Payout events #[cfg(feature = "payouts")] 30 => Self::PayoutSuccess, #[cfg(feature = "payouts")] 31 => Self::PayoutFailure, #[cfg(feature = "payouts")] 32 => Self::PayoutProcessing, #[cfg(feature = "payouts")] 33 => Self::PayoutCancelled, #[cfg(feature = "payouts")] 34 => Self::PayoutCreated, #[cfg(feature = "payouts")] 35 => Self::PayoutExpired, #[cfg(feature = "payouts")] 36 => Self::PayoutReversed, _ => Self::EventNotSupported, } } } pub enum WebhookFlow { Payment, #[cfg(feature = "payouts")] Payout, Refund, Dispute, Subscription, ReturnResponse, BankTransfer, Mandate, ExternalAuthentication, FraudCheck, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] Recovery, Setup, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] /// This enum tells about the affect a webhook had on an object pub enum WebhookResponseTracker { #[cfg(feature = "v1")] Payment { payment_id: common_utils::id_type::PaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "v2")] Payment { payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "payouts")] Payout { payout_id: common_utils::id_type::PayoutId, status: common_enums::PayoutStatus, }, #[cfg(feature = "v1")] Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v2")] Refund { payment_id: common_utils::id_type::GlobalPaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v1")] Dispute { dispute_id: String, payment_id: common_utils::id_type::PaymentId, status: common_enums::DisputeStatus, }, #[cfg(feature = "v2")] Dispute { dispute_id: String, payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::DisputeStatus, }, Mandate { mandate_id: String, status: common_enums::MandateStatus, }, #[cfg(feature = "v1")] PaymentMethod { payment_method_id: String, status: common_enums::PaymentMethodStatus, }, NoEffect, Relay { relay_id: common_utils::id_type::RelayId, status: common_enums::RelayStatus, }, } impl WebhookResponseTracker { #[cfg(feature = "v1")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } | Self::PaymentMethod { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } #[cfg(feature = "v1")] pub fn get_payment_method_id(&self) -> Option<String> { match self { Self::PaymentMethod { payment_method_id, .. } => Some(payment_method_id.to_owned()), Self::Payment { .. } | Self::Refund { .. } | Self::Dispute { .. } | Self::NoEffect | Self::Mandate { .. } | Self::Relay { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, } } #[cfg(feature = "v2")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } } impl From<IncomingWebhookEvent> for WebhookFlow { fn from(evt: IncomingWebhookEvent) -> Self { match evt { IncomingWebhookEvent::PaymentIntentFailure | IncomingWebhookEvent::PaymentIntentSuccess | IncomingWebhookEvent::PaymentIntentProcessing | IncomingWebhookEvent::PaymentActionRequired | IncomingWebhookEvent::PaymentIntentPartiallyFunded | IncomingWebhookEvent::PaymentIntentCancelled | IncomingWebhookEvent::PaymentIntentCancelFailure | IncomingWebhookEvent::PaymentIntentAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentAuthorizationFailure | IncomingWebhookEvent::PaymentIntentCaptureSuccess | IncomingWebhookEvent::PaymentIntentCaptureFailure | IncomingWebhookEvent::PaymentIntentExpired | IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure => Self::Payment, IncomingWebhookEvent::EventNotSupported => Self::ReturnResponse, IncomingWebhookEvent::RefundSuccess | IncomingWebhookEvent::RefundFailure => { Self::Refund } IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => { Self::Mandate } IncomingWebhookEvent::DisputeOpened | IncomingWebhookEvent::DisputeAccepted | IncomingWebhookEvent::DisputeExpired | IncomingWebhookEvent::DisputeCancelled | IncomingWebhookEvent::DisputeChallenged | IncomingWebhookEvent::DisputeWon | IncomingWebhookEvent::DisputeLost => Self::Dispute, IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, IncomingWebhookEvent::SourceChargeable | IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer, IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication, IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => { Self::FraudCheck } #[cfg(feature = "payouts")] IncomingWebhookEvent::PayoutSuccess | IncomingWebhookEvent::PayoutFailure | IncomingWebhookEvent::PayoutProcessing | IncomingWebhookEvent::PayoutCancelled | IncomingWebhookEvent::PayoutCreated | IncomingWebhookEvent::PayoutExpired | IncomingWebhookEvent::PayoutReversed => Self::Payout, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] IncomingWebhookEvent::RecoveryInvoiceCancel | IncomingWebhookEvent::RecoveryPaymentFailure | IncomingWebhookEvent::RecoveryPaymentPending | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery, IncomingWebhookEvent::SetupWebhook => Self::Setup, IncomingWebhookEvent::InvoiceGenerated => Self::Subscription, } } } pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum RefundIdType { RefundId(String), ConnectorRefundId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum MandateIdType { MandateId(String), ConnectorMandateId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum AuthenticationIdType { AuthenticationId(common_utils::id_type::AuthenticationId), ConnectorAuthenticationId(String), } #[cfg(feature = "payouts")] #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum PayoutIdType { PayoutAttemptId(String), ConnectorPayoutId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum ObjectReferenceId { PaymentId(payments::PaymentIdType), RefundId(RefundIdType), MandateId(MandateIdType), ExternalAuthenticationID(AuthenticationIdType), #[cfg(feature = "payouts")] PayoutId(PayoutIdType), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] InvoiceId(InvoiceIdType), SubscriptionId(common_utils::id_type::SubscriptionId), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum InvoiceIdType { ConnectorInvoiceId(String), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl ObjectReferenceId { pub fn get_connector_transaction_id_as_string( self, ) -> Result<String, common_utils::errors::ValidationError> { match self { Self::PaymentId( payments::PaymentIdType::ConnectorTransactionId(id) ) => Ok(id), Self::PaymentId(_)=>Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "ConnectorTransactionId variant of PaymentId is required but received otherr variant", }, ), Self::RefundId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received RefundId", }, ), Self::MandateId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received MandateId", }, ), Self::ExternalAuthenticationID(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received ExternalAuthenticationID", }, ), #[cfg(feature = "payouts")] Self::PayoutId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received PayoutId", }, ), Self::InvoiceId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received InvoiceId", }, ), Self::SubscriptionId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received SubscriptionId", }, ), } } } pub struct IncomingWebhookDetails { pub object_reference_id: ObjectReferenceId, pub resource_object: Vec<u8>, } #[derive(Debug, Serialize, ToSchema)] pub struct OutgoingWebhook { /// The merchant id of the merchant #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique event id for each webhook pub event_id: String, /// The type of event this webhook corresponds to. #[schema(value_type = EventType)] pub event_type: api_enums::EventType, /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow pub content: OutgoingWebhookContent, /// The time at which webhook was sent #[serde(default, with = "custom_serde::iso8601")] pub timestamp: PrimitiveDateTime, } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v1")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v2")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize)] pub struct ConnectorWebhookSecrets { pub secret: Vec<u8>, pub additional_secret: Option<masking::Secret<String>>, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl IncomingWebhookEvent { pub fn is_recovery_transaction_event(&self) -> bool { matches!( self, Self::RecoveryPaymentFailure | Self::RecoveryPaymentSuccess | Self::RecoveryPaymentPending ) } }
{ "crate": "api_models", "file": "crates/api_models/src/webhooks.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 9, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-7231369096977446896
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/api_keys.rs // Contains: 6 structs, 1 enums use common_utils::custom_serde; use masking::StrongSecret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The request body for creating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct CreateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, } /// The response body for creating an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct CreateApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The plaintext API Key used for server-side API access. Ensure you store the API Key /// securely as you will not be able to see it again. #[schema(value_type = String, max_length = 128)] pub api_key: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The response body for retrieving an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RetrieveApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The first few characters of the plaintext API Key to help you identify it. #[schema(value_type = String, max_length = 64)] pub prefix: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The request body for updating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct UpdateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: Option<String>, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: Option<ApiKeyExpiration>, #[serde(skip_deserializing)] #[schema(value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, } /// The response body for revoking an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RevokeApiKeyResponse { /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// Indicates whether the API key was revoked or not. #[schema(example = "true")] pub revoked: bool, } /// The constraints that are applicable when listing API Keys associated with a merchant account. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ListApiKeyConstraints { /// The maximum number of API Keys to include in the response. pub limit: Option<i64>, /// The number of API Keys to skip when retrieving the list of API keys. pub skip: Option<i64>, } /// The expiration date and time for an API Key. #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum ApiKeyExpiration { /// The API Key does not expire. #[serde(with = "never")] Never, /// The API Key expires at the specified date and time. #[serde(with = "custom_serde::iso8601")] DateTime(PrimitiveDateTime), } impl From<ApiKeyExpiration> for Option<PrimitiveDateTime> { fn from(expiration: ApiKeyExpiration) -> Self { match expiration { ApiKeyExpiration::Never => None, ApiKeyExpiration::DateTime(date_time) => Some(date_time), } } } impl From<Option<PrimitiveDateTime>> for ApiKeyExpiration { fn from(date_time: Option<PrimitiveDateTime>) -> Self { date_time.map_or(Self::Never, Self::DateTime) } } // This implementation is required as otherwise, `serde` would serialize and deserialize // `ApiKeyExpiration::Never` as `null`, which is not preferable. // Reference: https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291 mod never { const NEVER: &str = "never"; pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(NEVER) } pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> where D: serde::Deserializer<'de>, { struct NeverVisitor; impl serde::de::Visitor<'_> for NeverVisitor { type Value = (); fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, r#""{NEVER}""#) } fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { if value == NEVER { Ok(()) } else { Err(E::invalid_value(serde::de::Unexpected::Str(value), &self)) } } } deserializer.deserialize_str(NeverVisitor) } } impl<'a> ToSchema<'a> for ApiKeyExpiration { fn schema() -> ( &'a str, utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>, ) { use utoipa::openapi::{KnownFormat, ObjectBuilder, OneOfBuilder, SchemaFormat, SchemaType}; ( "ApiKeyExpiration", OneOfBuilder::new() .item( ObjectBuilder::new() .schema_type(SchemaType::String) .enum_values(Some(["never"])), ) .item( ObjectBuilder::new() .schema_type(SchemaType::String) .format(Some(SchemaFormat::KnownFormat(KnownFormat::DateTime))), ) .into(), ) } } #[cfg(test)] mod api_key_expiration_tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_serialization() { assert_eq!( serde_json::to_string(&ApiKeyExpiration::Never).unwrap(), r#""never""# ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new( date, time ))) .unwrap(), r#""2022-09-10T11:12:13.000Z""# ); } #[test] fn test_deserialization() { assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""never""#).unwrap(), ApiKeyExpiration::Never ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(), ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time)) ); } #[test] fn test_null() { let result = serde_json::from_str::<ApiKeyExpiration>("null"); assert!(result.is_err()); let result = serde_json::from_str::<Option<ApiKeyExpiration>>("null").unwrap(); assert_eq!(result, None); } }
{ "crate": "api_models", "file": "crates/api_models/src/api_keys.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_api_models_5827519295279039671
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics.rs // Contains: 54 structs, 2 enums 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>, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 54, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-371809284769464924
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/customers.rs // Contains: 13 structs, 0 enums use common_utils::{crypto, custom_serde, id_type, pii, types::Description}; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::payments; /// The customer details #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerRequest { /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// 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>, /// Customer's tax registration ID #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequest { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequestWithConstraints { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, /// Unique identifier for a customer pub customer_id: Option<id_type::CustomerId>, /// Filter with created time range #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, } #[cfg(feature = "v1")] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some( self.customer_id .to_owned() .unwrap_or_else(common_utils::generate_customer_id_of_default_length), ) } pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { self.email.clone() } } /// The customer details #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerRequest { /// The merchant identifier for the customer object. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Secret<String>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: pii::Email, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// 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 customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { Some(self.email.clone()) } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// 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 identifier for the default payment method. #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] pub default_payment_method_id: Option<String>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v1")] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some(self.customer_id.clone()) } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Connector specific customer reference ids #[schema(value_type = Option<Object>, example = json!({"mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506"}))] pub connector_customer_ids: Option<common_types::customers::ConnectorCustomerMap>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String> ,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// 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 identifier for the default payment method. #[schema(value_type = Option<String>, max_length = 64, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v2")] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerUpdateRequest { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// 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>, /// Customer's tax registration ID #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v1")] impl CustomerUpdateRequest { pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerUpdateRequest { /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// 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 payment method #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] impl CustomerUpdateRequest { pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub customer_id: id_type::CustomerId, pub request: CustomerUpdateRequest, } #[cfg(feature = "v2")] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub id: id_type::GlobalCustomerId, pub request: CustomerUpdateRequest, } #[derive(Debug, Serialize, ToSchema)] pub struct CustomerListResponse { /// List of customers pub data: Vec<CustomerResponse>, /// Total count of customers pub total_count: usize, }
{ "crate": "api_models", "file": "crates/api_models/src/customers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 13, "num_tables": null, "score": null, "total_crates": null }
file_api_models_5873415637691101906
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/gsm.rs // Contains: 6 structs, 0 enums 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>, } #[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>, } #[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>, }
{ "crate": "api_models", "file": "crates/api_models/src/gsm.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_api_models_8272826214876625304
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/currency.rs // Contains: 2 structs, 0 enums 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 {}
{ "crate": "api_models", "file": "crates/api_models/src/currency.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_api_models_6722645396776223812
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/profile_acquirer.rs // Contains: 3 structs, 0 enums use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct ProfileAcquirerCreate { /// The merchant id assigned by the acquirer #[schema(value_type= String,example = "M123456789")] pub acquirer_assigned_merchant_id: String, /// merchant name #[schema(value_type= String,example = "NewAge Retailer")] pub merchant_name: String, /// Network provider #[schema(value_type= String,example = "VISA")] pub network: common_enums::enums::CardNetwork, /// Acquirer bin #[schema(value_type= String,example = "456789")] pub acquirer_bin: String, /// Acquirer ica provided by acquirer #[schema(value_type= Option<String>,example = "401288")] pub acquirer_ica: Option<String>, /// Fraud rate for the particular acquirer configuration #[schema(value_type= f64,example = 0.01)] pub acquirer_fraud_rate: f64, /// Parent profile id to link the acquirer account with #[schema(value_type= String,example = "pro_ky0yNyOXXlA5hF8JzE5q")] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Serialize, Deserialize, ToSchema, Clone)] pub struct ProfileAcquirerResponse { /// The unique identifier of the profile acquirer #[schema(value_type= String,example = "pro_acq_LCRdERuylQvNQ4qh3QE0")] pub profile_acquirer_id: common_utils::id_type::ProfileAcquirerId, /// The merchant id assigned by the acquirer #[schema(value_type= String,example = "M123456789")] pub acquirer_assigned_merchant_id: String, /// Merchant name #[schema(value_type= String,example = "NewAge Retailer")] pub merchant_name: String, /// Network provider #[schema(value_type= String,example = "VISA")] pub network: common_enums::enums::CardNetwork, /// Acquirer bin #[schema(value_type= String,example = "456789")] pub acquirer_bin: String, /// Acquirer ica provided by acquirer #[schema(value_type= Option<String>,example = "401288")] pub acquirer_ica: Option<String>, /// Fraud rate for the particular acquirer configuration #[schema(value_type= f64,example = 0.01)] pub acquirer_fraud_rate: f64, /// Parent profile id to link the acquirer account with #[schema(value_type= String,example = "pro_ky0yNyOXXlA5hF8JzE5q")] pub profile_id: common_utils::id_type::ProfileId, } impl common_utils::events::ApiEventMetric for ProfileAcquirerCreate {} impl common_utils::events::ApiEventMetric for ProfileAcquirerResponse {} impl From<( common_utils::id_type::ProfileAcquirerId, &common_utils::id_type::ProfileId, &common_types::domain::AcquirerConfig, )> for ProfileAcquirerResponse { fn from( (profile_acquirer_id, profile_id, acquirer_config): ( common_utils::id_type::ProfileAcquirerId, &common_utils::id_type::ProfileId, &common_types::domain::AcquirerConfig, ), ) -> Self { Self { profile_acquirer_id, profile_id: profile_id.clone(), acquirer_assigned_merchant_id: acquirer_config.acquirer_assigned_merchant_id.clone(), merchant_name: acquirer_config.merchant_name.clone(), network: acquirer_config.network.clone(), acquirer_bin: acquirer_config.acquirer_bin.clone(), acquirer_ica: acquirer_config.acquirer_ica.clone(), acquirer_fraud_rate: acquirer_config.acquirer_fraud_rate, } } } #[derive(Debug, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProfileAcquirerUpdate { #[schema(value_type = Option<String>, example = "M987654321")] pub acquirer_assigned_merchant_id: Option<String>, #[schema(value_type = Option<String>, example = "Updated Retailer Name")] pub merchant_name: Option<String>, #[schema(value_type = Option<String>, example = "MASTERCARD")] pub network: Option<common_enums::enums::CardNetwork>, #[schema(value_type = Option<String>, example = "987654")] pub acquirer_bin: Option<String>, #[schema(value_type = Option<String>, example = "501299")] pub acquirer_ica: Option<String>, #[schema(value_type = Option<f64>, example = "0.02")] pub acquirer_fraud_rate: Option<f64>, } impl common_utils::events::ApiEventMetric for ProfileAcquirerUpdate {}
{ "crate": "api_models", "file": "crates/api_models/src/profile_acquirer.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_2673341667090594883
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/authentication.rs // Contains: 12 structs, 1 enums 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::{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>, } #[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>, } 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")] #[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>, } #[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 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>, /// 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>, /// 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 = Option<String>)] pub authentication_value: Option<masking::Secret<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")] 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>>, /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, } impl ApiEventMetric for AuthenticationSyncRequest { 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 AuthenticationSyncPostUpdateRequest { /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, } impl ApiEventMetric for AuthenticationSyncPostUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } }
{ "crate": "api_models", "file": "crates/api_models/src/authentication.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 12, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-2418982772947466949
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/routing.rs // Contains: 62 structs, 24 enums use std::fmt::Debug; use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule}; use common_utils::{ errors::{ParsingError, ValidationError}, ext_traits::ValueExt, pii, }; use euclid::frontend::ast::Program; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{RoutableConnectors, TransactionType}, open_router, }; // Define constants for default values const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0; const DEFAULT_BUCKET_SIZE: i32 = 200; const DEFAULT_HEDGING_PERCENT: f64 = 5.0; const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35; const DEFAULT_PAYMENT_METHOD: &str = "CARD"; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } impl ConnectorSelection { pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> { match self { Self::Priority(list) => list.clone(), Self::VolumeSplit(splits) => { splits.iter().map(|split| split.connector.clone()).collect() } } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: String, pub description: String, pub algorithm: StaticRoutingAlgorithm, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: Option<String>, pub description: Option<String>, pub algorithm: Option<StaticRoutingAlgorithm>, #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, pub transaction_type: Option<TransactionType>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct ProfileDefaultRoutingConfig { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub connectors: Vec<RoutableConnectorChoice>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveQuery { pub limit: Option<u16>, pub offset: Option<u8>, pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingActivatePayload { pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQuery { pub profile_id: Option<common_utils::id_type::ProfileId>, pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQueryWrapper { pub routing_query: RoutingRetrieveQuery, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Response of the retrieved routing configs for a merchant account pub struct RoutingRetrieveResponse { pub algorithm: Option<MerchantRoutingAlgorithm>, } #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum LinkedRoutingConfigRetrieveResponse { MerchantAccountBased(Box<RoutingRetrieveResponse>), ProfileBased(Vec<RoutingDictionaryRecord>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Routing Algorithm specific to merchants pub struct MerchantRoutingAlgorithm { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub description: String, pub algorithm: RoutingAlgorithmWrapper, pub created_at: i64, pub modified_at: i64, pub algorithm_for: TransactionType, } impl EuclidDirFilter for ConnectorSelection { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::CardBin, DirKeyKind::CardType, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::UpiType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::AuthenticationType, DirKeyKind::MandateAcceptanceType, DirKeyKind::MandateType, DirKeyKind::PaymentType, DirKeyKind::SetupFutureUsage, DirKeyKind::CaptureMethod, DirKeyKind::BillingCountry, DirKeyKind::BusinessCountry, DirKeyKind::BusinessLabel, DirKeyKind::MetaData, DirKeyKind::RewardType, DirKeyKind::VoucherType, DirKeyKind::CardRedirectType, DirKeyKind::BankTransferType, DirKeyKind::RealTimePaymentType, ]; } impl EuclidAnalysable for ConnectorSelection { fn get_dir_value_for_analysis( &self, rule_name: String, ) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> { self.get_connector_list() .into_iter() .map(|connector_choice| { let connector_name = connector_choice.connector.to_string(); let mca_id = connector_choice.merchant_connector_id.clone(); ( euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())), std::collections::HashMap::from_iter([( "CONNECTOR_SELECTION".to_string(), serde_json::json!({ "rule_name": rule_name, "connector_name": connector_name, "mca_id": mca_id, }), )]), ) }) .collect() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } /// Routable Connector chosen for a payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)] pub enum RoutableChoiceKind { OnlyConnector, FullStruct, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(untagged)] pub enum RoutableChoiceSerde { OnlyConnector(Box<RoutableConnectors>), FullStruct { connector: RoutableConnectors, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } impl std::fmt::Display for RoutableConnectorChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let base = self.connector.to_string(); if let Some(mca_id) = &self.merchant_connector_id { return write!(f, "{}:{}", base, mca_id.get_string_repr()); } write!(f, "{base}") } } impl From<RoutableConnectorChoice> for ast::ConnectorChoice { fn from(value: RoutableConnectorChoice) -> Self { Self { connector: value.connector, } } } impl PartialEq for RoutableConnectorChoice { fn eq(&self, other: &Self) -> bool { self.connector.eq(&other.connector) && self.merchant_connector_id.eq(&other.merchant_connector_id) } } impl Eq for RoutableConnectorChoice {} impl From<RoutableChoiceSerde> for RoutableConnectorChoice { fn from(value: RoutableChoiceSerde) -> Self { match value { RoutableChoiceSerde::OnlyConnector(connector) => Self { choice_kind: RoutableChoiceKind::OnlyConnector, connector: *connector, merchant_connector_id: None, }, RoutableChoiceSerde::FullStruct { connector, merchant_connector_id, } => Self { choice_kind: RoutableChoiceKind::FullStruct, connector, merchant_connector_id, }, } } } impl From<RoutableConnectorChoice> for RoutableChoiceSerde { fn from(value: RoutableConnectorChoice) -> Self { match value.choice_kind { RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)), RoutableChoiceKind::FullStruct => Self::FullStruct { connector: value.connector, merchant_connector_id: value.merchant_connector_id, }, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithStatus { pub routable_connector_choice: RoutableConnectorChoice, pub status: bool, } impl RoutableConnectorChoiceWithStatus { pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self { Self { routable_connector_choice, status, } } } #[derive( Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, ThreeDsDecisionRule, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingPayloadWrapper { pub updated_config: Vec<RoutableConnectorChoice>, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum RoutingAlgorithmWrapper { Static(StaticRoutingAlgorithm), Dynamic(DynamicRoutingAlgorithm), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum DynamicRoutingAlgorithm { EliminationBasedAlgorithm(EliminationRoutingConfig), SuccessBasedAlgorithm(SuccessBasedRoutingConfig), ContractBasedAlgorithm(ContractBasedRoutingConfig), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "RoutingAlgorithmSerde" )] pub enum StaticRoutingAlgorithm { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), #[schema(value_type=ProgramConnectorSelection)] Advanced(Program<ConnectorSelection>), #[schema(value_type=ProgramThreeDsDecisionRule)] ThreeDsDecisionRule(Program<ThreeDSDecisionRule>), } #[derive(Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct ProgramThreeDsDecisionRule { pub default_selection: ThreeDSDecisionRule, #[schema(value_type = RuleThreeDsDecisionRule)] pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>, #[schema(value_type = HashMap<String, serde_json::Value>)] pub metadata: std::collections::HashMap<String, serde_json::Value>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct RuleThreeDsDecisionRule { pub name: String, pub connector_selection: ThreeDSDecision, #[schema(value_type = Vec<IfStatement>)] pub statements: Vec<ast::IfStatement>, } impl StaticRoutingAlgorithm { pub fn should_validate_connectors_in_routing_config(&self) -> bool { match self { Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true, Self::ThreeDsDecisionRule(_) => false, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmSerde { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), Advanced(Program<ConnectorSelection>), ThreeDsDecisionRule(Program<ThreeDSDecisionRule>), } impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> { match &value { RoutingAlgorithmSerde::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match value { RoutingAlgorithmSerde::Single(i) => Self::Single(i), RoutingAlgorithmSerde::Priority(i) => Self::Priority(i), RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i), RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i), RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(i), }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "StraightThroughAlgorithmSerde", into = "StraightThroughAlgorithmSerde" )] pub enum StraightThroughAlgorithm { #[schema(title = "Single")] Single(Box<RoutableConnectorChoice>), #[schema(title = "Priority")] Priority(Vec<RoutableConnectorChoice>), #[schema(title = "VolumeSplit")] VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum StraightThroughAlgorithmInner { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum StraightThroughAlgorithmSerde { Direct(StraightThroughAlgorithmInner), Nested { algorithm: StraightThroughAlgorithmInner, }, } impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> { let inner = match value { StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm, StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm, }; match &inner { StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match inner { StraightThroughAlgorithmInner::Single(single) => Self::Single(single), StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist), StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit), }) } } impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde { fn from(value: StraightThroughAlgorithm) -> Self { let inner = match value { StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn), StraightThroughAlgorithm::Priority(plist) => { StraightThroughAlgorithmInner::Priority(plist) } StraightThroughAlgorithm::VolumeSplit(vsplit) => { StraightThroughAlgorithmInner::VolumeSplit(vsplit) } }; Self::Nested { algorithm: inner } } } impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm { fn from(value: StraightThroughAlgorithm) -> Self { match value { StraightThroughAlgorithm::Single(conn) => Self::Single(conn), StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns), StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits), } } } impl StaticRoutingAlgorithm { pub fn get_kind(&self) -> RoutingAlgorithmKind { match self { Self::Single(_) => RoutingAlgorithmKind::Single, Self::Priority(_) => RoutingAlgorithmKind::Priority, Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit, Self::Advanced(_) => RoutingAlgorithmKind::Advanced, Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule, } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingAlgorithmRef { pub algorithm_id: Option<common_utils::id_type::RoutingId>, pub timestamp: i64, pub config_algo_id: Option<String>, pub surcharge_config_algo_id: Option<String>, } impl RoutingAlgorithmRef { pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) { self.algorithm_id = Some(new_id); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_conditional_config_id(&mut self, ids: String) { self.config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_surcharge_config_id(&mut self, ids: String) { self.surcharge_config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn parse_routing_algorithm( value: Option<pii::SecretSerdeValue>, ) -> Result<Option<Self>, error_stack::Report<ParsingError>> { value .map(|val| val.parse_value::<Self>("RoutingAlgorithmRef")) .transpose() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionaryRecord { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub kind: RoutingAlgorithmKind, pub description: String, pub created_at: i64, pub modified_at: i64, pub algorithm_for: Option<TransactionType>, pub decision_engine_routing_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionary { #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, pub active_id: Option<String>, pub records: Vec<RoutingDictionaryRecord>, } #[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)] #[serde(untagged)] pub enum RoutingKind { Config(RoutingDictionary), RoutingAlgorithm(Vec<RoutingDictionaryRecord>), } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct RoutingAlgorithmId { #[schema(value_type = String)] pub routing_algorithm_id: common_utils::id_type::RoutingId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingLinkWrapper { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: RoutingAlgorithmId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicAlgorithmWithTimestamp<T> { pub algorithm_id: Option<T>, pub timestamp: i64, } impl<T> DynamicAlgorithmWithTimestamp<T> { pub fn new(algorithm_id: Option<T>) -> Self { Self { algorithm_id, timestamp: common_utils::date_time::now_unix_timestamp(), } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { pub success_based_algorithm: Option<SuccessBasedAlgorithm>, pub dynamic_routing_volume_split: Option<u8>, pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, pub contract_based_routing: Option<ContractRoutingAlgorithm>, #[serde(default)] pub is_merchant_created_in_decision_engine: bool, } pub trait DynamicRoutingAlgoAccessor { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>; fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures; } impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl EliminationRoutingAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl SuccessBasedAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl DynamicRoutingAlgorithmRef { pub fn update(&mut self, new: Self) { if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(elimination_routing_algorithm) } if let Some(success_based_algorithm) = new.success_based_algorithm { self.success_based_algorithm = Some(success_based_algorithm) } if let Some(contract_based_routing) = new.contract_based_routing { self.contract_based_routing = Some(contract_based_routing) } } pub fn update_enabled_features( &mut self, algo_type: DynamicRoutingType, feature_to_enable: DynamicRoutingFeatures, ) { match algo_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } } } pub fn update_volume_split(&mut self, volume: Option<u8>) { self.dynamic_routing_volume_split = volume } pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) { self.is_merchant_created_in_decision_engine = is_created; } pub fn is_success_rate_routing_enabled(&self) -> bool { self.success_based_algorithm .as_ref() .map(|success_based_routing| { success_based_routing.enabled_feature == DynamicRoutingFeatures::DynamicConnectorSelection || success_based_routing.enabled_feature == DynamicRoutingFeatures::Metrics }) .unwrap_or_default() } pub fn is_elimination_enabled(&self) -> bool { self.elimination_routing_algorithm .as_ref() .map(|elimination_routing| { elimination_routing.enabled_feature == DynamicRoutingFeatures::DynamicConnectorSelection || elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics }) .unwrap_or_default() } } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplit { pub routing_type: RoutingType, pub split: u8, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplitWrapper { pub routing_info: RoutingVolumeSplit, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum RoutingType { #[default] Static, Dynamic, } impl RoutingType { pub fn is_dynamic_routing(self) -> bool { self == Self::Dynamic } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } impl EliminationRoutingAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl SuccessBasedAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl DynamicRoutingAlgorithmRef { pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } pub fn update_feature( &mut self, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } }; } pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { if let Some(success_based_algo) = &self.success_based_algorithm { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: success_based_algo.enabled_feature, }); } } DynamicRoutingType::EliminationRouting => { if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: elimination_based_algo.enabled_feature, }); } } DynamicRoutingType::ContractBasedRouting => { if let Some(contract_based_algo) = &self.contract_based_routing { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: contract_based_algo.enabled_feature, }); } } } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingVolumeSplitQuery { pub split: u8, } #[derive( Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum DynamicRoutingFeatures { Metrics, DynamicConnectorSelection, #[default] None, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingUpdateConfigQuery { #[schema(value_type = String)] pub algorithm_id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ToggleDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ToggleDynamicRoutingPath { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct CreateDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, pub payload: DynamicRoutingPayload, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum DynamicRoutingPayload { SuccessBasedRoutingPayload(SuccessBasedRoutingConfig), EliminationRoutingPayload(EliminationRoutingConfig), } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct RoutingVolumeSplitResponse { pub split: u8, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, #[schema(value_type = DecisionEngineEliminationData)] pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationAnalyserConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } impl EliminationAnalyserConfig { pub fn update(&mut self, new: Self) { if let Some(bucket_size) = new.bucket_size { self.bucket_size = Some(bucket_size) } if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs { self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs) } } } impl Default for EliminationRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(60), }), decision_engine_configs: None, } } } impl EliminationRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.elimination_analyser_config { self.elimination_analyser_config .as_mut() .map(|config| config.update(new_config)); } if let Some(new_config) = new.decision_engine_configs { self.decision_engine_configs .as_mut() .map(|config| config.update(new_config)); } } pub fn open_router_config_default() -> Self { Self { elimination_analyser_config: None, params: None, decision_engine_configs: Some(open_router::DecisionEngineEliminationData { threshold: DEFAULT_ELIMINATION_THRESHOLD, }), } } pub fn get_decision_engine_configs( &self, ) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>> { self.decision_engine_configs .clone() .ok_or(error_stack::Report::new( ValidationError::MissingRequiredField { field_name: "decision_engine_configs".to_string(), }, )) } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, #[schema(value_type = DecisionEngineSuccessRateData)] pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>, } impl Default for SuccessBasedRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(5), default_success_rate: Some(100.0), max_aggregates_size: Some(8), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: None, max_total_count: Some(5), }), specificity_level: SuccessRateSpecificityLevel::default(), exploration_percent: Some(20.0), shuffle_on_tie_during_exploitation: Some(false), }), decision_engine_configs: None, } } } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, strum::Display, )] pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, AuthenticationType, Currency, Country, CardNetwork, CardBin, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfigBody { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<CurrentBlockThreshold>, #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, pub shuffle_on_tie_during_exploitation: Option<bool>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct CurrentBlockThreshold { pub duration_in_mins: Option<u64>, pub max_total_count: Option<u64>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, Copy, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SuccessRateSpecificityLevel { #[default] Merchant, Global, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedRoutingPayloadWrapper { pub updated_config: SuccessBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingPayloadWrapper { pub updated_config: EliminationRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingPayloadWrapper { pub updated_config: ContractBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingSetupPayloadWrapper { pub config: Option<ContractBasedRoutingConfig>, pub profile_id: common_utils::id_type::ProfileId, pub features_to_enable: DynamicRoutingFeatures, } #[derive( Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq, )] pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, ContractBasedRouting, } impl SuccessBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_config) = new.decision_engine_configs { self.decision_engine_configs .as_mut() .map(|config| config.update(new_config)); } } pub fn open_router_config_default() -> Self { Self { params: None, config: None, decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData { default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD), default_bucket_size: Some(DEFAULT_BUCKET_SIZE), default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT), default_lower_reset_factor: None, default_upper_reset_factor: None, default_gateway_extra_score: None, sub_level_input_config: Some(vec![ open_router::DecisionEngineSRSubLevelInputConfig { payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()), payment_method: None, latency_threshold: None, bucket_size: Some(DEFAULT_BUCKET_SIZE), hedging_percent: Some(DEFAULT_HEDGING_PERCENT), lower_reset_factor: None, upper_reset_factor: None, gateway_extra_score: None, }, ]), }), } } pub fn get_decision_engine_configs( &self, ) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>> { self.decision_engine_configs .clone() .ok_or(error_stack::Report::new( ValidationError::MissingRequiredField { field_name: "decision_engine_configs".to_string(), }, )) } } impl SuccessBasedRoutingConfigBody { pub fn update(&mut self, new: Self) { if let Some(min_aggregates_size) = new.min_aggregates_size { self.min_aggregates_size = Some(min_aggregates_size) } if let Some(default_success_rate) = new.default_success_rate { self.default_success_rate = Some(default_success_rate) } if let Some(max_aggregates_size) = new.max_aggregates_size { self.max_aggregates_size = Some(max_aggregates_size) } if let Some(current_block_threshold) = new.current_block_threshold { self.current_block_threshold .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } self.specificity_level = new.specificity_level; if let Some(exploration_percent) = new.exploration_percent { self.exploration_percent = Some(exploration_percent); } if let Some(shuffle_on_tie_during_exploitation) = new.shuffle_on_tie_during_exploitation { self.shuffle_on_tie_during_exploitation = Some(shuffle_on_tie_during_exploitation); } } } impl CurrentBlockThreshold { pub fn update(&mut self, new: Self) { if let Some(max_total_count) = new.max_total_count { self.max_total_count = Some(max_total_count) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfig { pub config: Option<ContractBasedRoutingConfigBody>, pub label_info: Option<Vec<LabelInformation>>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfigBody { pub constants: Option<Vec<f64>>, pub time_scale: Option<ContractBasedTimeScale>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct LabelInformation { pub label: String, pub target_count: u64, pub target_time: u64, #[schema(value_type = String)] pub mca_id: common_utils::id_type::MerchantConnectorAccountId, } impl LabelInformation { pub fn update_target_time(&mut self, new: &Self) { self.target_time = new.target_time; } pub fn update_target_count(&mut self, new: &Self) { self.target_count = new.target_count; } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ContractBasedTimeScale { Day, Month, } impl Default for ContractBasedRoutingConfig { fn default() -> Self { Self { config: Some(ContractBasedRoutingConfigBody { constants: Some(vec![0.7, 0.35]), time_scale: Some(ContractBasedTimeScale::Day), }), label_info: None, } } } impl ContractBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_label_info) = new.label_info { new_label_info.iter().for_each(|new_label_info| { if let Some(existing_label_infos) = &mut self.label_info { let mut updated = false; for existing_label_info in &mut *existing_label_infos { if existing_label_info.mca_id == new_label_info.mca_id { existing_label_info.update_target_time(new_label_info); existing_label_info.update_target_count(new_label_info); updated = true; } } if !updated { existing_label_infos.push(new_label_info.clone()); } } else { self.label_info = Some(vec![new_label_info.clone()]); } }); } } } impl ContractBasedRoutingConfigBody { pub fn update(&mut self, new: Self) { if let Some(new_cons) = new.constants { self.constants = Some(new_cons) } if let Some(new_time_scale) = new.time_scale { self.time_scale = Some(new_time_scale) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithBucketName { pub routable_connector_choice: RoutableConnectorChoice, pub bucket_name: String, } impl RoutableConnectorChoiceWithBucketName { pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateConfigEventRequest { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<CalSuccessRateConfigEventRequest>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventBucketConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<EliminationRoutingEventBucketConfig>, } /// API-1 types #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalContractScoreEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<ContractBasedRoutingConfig>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LabelWithScoreEventResponse { pub score: f64, pub label: String, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventResponse { pub labels_with_score: Vec<LabelWithScoreEventResponse>, pub routing_approach: RoutingApproach, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RoutingApproach { Exploitation, Exploration, Elimination, ContractBased, Default, } impl RoutingApproach { pub fn from_decision_engine_approach(approach: &str) -> Self { match approach { "SR_SELECTION_V3_ROUTING" => Self::Exploitation, "SR_V3_HEDGING" => Self::Exploration, _ => Self::Default, } } } impl std::fmt::Display for RoutingApproach { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Exploitation => write!(f, "Exploitation"), Self::Exploration => write!(f, "Exploration"), Self::Elimination => write!(f, "Elimination"), Self::ContractBased => write!(f, "ContractBased"), Self::Default => write!(f, "Default"), } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RuleMigrationQuery { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub limit: Option<u32>, pub offset: Option<u32>, } impl RuleMigrationQuery { pub fn validated_limit(&self) -> u32 { self.limit.unwrap_or(50).min(1000) } } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationResult { pub success: Vec<RuleMigrationResponse>, pub errors: Vec<RuleMigrationError>, } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationResponse { pub profile_id: common_utils::id_type::ProfileId, pub euclid_algorithm_id: common_utils::id_type::RoutingId, pub decision_engine_algorithm_id: String, pub is_active_rule: bool, } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationError { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: common_utils::id_type::RoutingId, pub error: String, } impl RuleMigrationResponse { pub fn new( profile_id: common_utils::id_type::ProfileId, euclid_algorithm_id: common_utils::id_type::RoutingId, decision_engine_algorithm_id: String, is_active_rule: bool, ) -> Self { Self { profile_id, euclid_algorithm_id, decision_engine_algorithm_id, is_active_rule, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingResultSource { /// External Decision Engine DecisionEngine, /// Inbuilt Hyperswitch Routing Engine HyperswitchRouting, } //TODO: temporary change will be refactored afterwards #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] pub struct RoutingEvaluateRequest { pub created_by: String, #[schema(value_type = Object)] ///Parameters that can be used in the routing evaluate request. ///eg: {"parameters": { /// "payment_method": {"type": "enum_variant", "value": "card"}, /// "payment_method_type": {"type": "enum_variant", "value": "credit"}, /// "amount": {"type": "number", "value": 10}, /// "currency": {"type": "str_value", "value": "INR"}, /// "authentication_type": {"type": "enum_variant", "value": "three_ds"}, /// "card_bin": {"type": "str_value", "value": "424242"}, /// "capture_method": {"type": "enum_variant", "value": "scheduled"}, /// "business_country": {"type": "str_value", "value": "IN"}, /// "billing_country": {"type": "str_value", "value": "IN"}, /// "business_label": {"type": "str_value", "value": "business_label"}, /// "setup_future_usage": {"type": "enum_variant", "value": "off_session"}, /// "card_network": {"type": "enum_variant", "value": "visa"}, /// "payment_type": {"type": "enum_variant", "value": "recurring_mandate"}, /// "mandate_type": {"type": "enum_variant", "value": "single_use"}, /// "mandate_acceptance_type": {"type": "enum_variant", "value": "online"}, /// "metadata":{"type": "metadata_variant", "value": {"key": "key1", "value": "value1"}} /// }} pub parameters: std::collections::HashMap<String, Option<ValueType>>, pub fallback_output: Vec<DeRoutableConnectorChoice>, } impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {} #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RoutingEvaluateResponse { pub status: String, pub output: serde_json::Value, #[serde(deserialize_with = "deserialize_connector_choices")] pub evaluated_output: Vec<RoutableConnectorChoice>, #[serde(deserialize_with = "deserialize_connector_choices")] pub eligible_connectors: Vec<RoutableConnectorChoice>, } impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {} fn deserialize_connector_choices<'de, D>( deserializer: D, ) -> Result<Vec<RoutableConnectorChoice>, D::Error> where D: serde::Deserializer<'de>, { let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?; Ok(infos .into_iter() .map(RoutableConnectorChoice::from) .collect()) } impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice { fn from(choice: DeRoutableConnectorChoice) -> Self { Self { choice_kind: RoutableChoiceKind::FullStruct, connector: choice.gateway_name, merchant_connector_id: choice.gateway_id, } } } /// Routable Connector chosen for a payment #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DeRoutableConnectorChoice { pub gateway_name: RoutableConnectors, #[schema(value_type = String)] pub gateway_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } /// Represents a value in the DSL #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum ValueType { /// Represents a number literal Number(u64), /// Represents an enum variant EnumVariant(String), /// Represents a Metadata variant MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(String), /// Represents a global reference, which is a reference to a global variable GlobalRef(String), /// Represents an array of numbers. This is basically used for /// "one of the given numbers" operations /// eg: payment.method.amount = (1, 2, 3) NumberArray(Vec<u64>), /// Similar to NumberArray but for enum variants /// eg: payment.method.cardtype = (debit, credit) EnumVariantArray(Vec<String>), /// Like a number array but can include comparisons. Useful for /// conditions like "500 < amount < 1000" /// eg: payment.amount = (> 500, < 1000) NumberComparisonArray(Vec<NumberComparison>), } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] pub struct MetadataValue { pub key: String, pub value: String, } /// Represents a number comparison for "NumberComparisonArrayValue" #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct NumberComparison { pub comparison_type: ComparisonType, pub number: u64, } /// Conditional comparison type #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ComparisonType { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, }
{ "crate": "api_models", "file": "crates/api_models/src/routing.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 24, "num_structs": 62, "num_tables": null, "score": null, "total_crates": null }
file_api_models_2791986648884015638
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/health_check.rs // Contains: 2 structs, 1 enums use std::collections::hash_map::HashMap; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RouterHealthCheckResponse { pub database: bool, pub redis: bool, #[serde(skip_serializing_if = "Option::is_none")] pub vault: Option<bool>, #[cfg(feature = "olap")] pub analytics: bool, #[cfg(feature = "olap")] pub opensearch: bool, pub outgoing_request: bool, #[cfg(feature = "dynamic_routing")] pub grpc_health_check: HealthCheckMap, #[cfg(feature = "dynamic_routing")] pub decision_engine: bool, pub unified_connector_service: Option<bool>, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} /// gRPC based services eligible for Health check #[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum HealthCheckServices { /// Dynamic routing service DynamicRoutingService, } pub type HealthCheckMap = HashMap<HealthCheckServices, bool>; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SchedulerHealthCheckResponse { pub database: bool, pub redis: bool, pub outgoing_request: bool, } pub enum HealthState { Running, Error, NotApplicable, } impl From<HealthState> for bool { fn from(value: HealthState) -> Self { match value { HealthState::Running => true, HealthState::Error | HealthState::NotApplicable => false, } } } impl From<HealthState> for Option<bool> { fn from(value: HealthState) -> Self { match value { HealthState::Running => Some(true), HealthState::Error => Some(false), HealthState::NotApplicable => None, } } } impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {}
{ "crate": "api_models", "file": "crates/api_models/src/health_check.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-1628816396584880500
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/ephemeral_key.rs // Contains: 4 structs, 1 enums use common_utils::id_type; #[cfg(feature = "v2")] use masking::Secret; use serde; use utoipa::ToSchema; #[cfg(feature = "v1")] /// Information required to create an ephemeral key. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EphemeralKeyCreateRequest { /// Customer ID for which an ephemeral key must be created #[schema( min_length = 1, max_length = 64, value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44" )] pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ResourceId { #[schema(value_type = String)] Customer(id_type::GlobalCustomerId), } #[cfg(feature = "v2")] /// Information required to create a client secret. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClientSecretCreateRequest { /// Resource ID for which a client secret must be created pub resource_id: ResourceId, } #[cfg(feature = "v2")] /// client_secret for the resource_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct ClientSecretResponse { /// Client Secret id #[schema(value_type = String, max_length = 32, min_length = 1)] pub id: id_type::ClientSecretId, /// resource_id to which this client secret belongs to #[schema(value_type = ResourceId)] pub resource_id: ResourceId, /// time at which this client secret was created pub created_at: time::PrimitiveDateTime, /// time at which this client secret would expire pub expires: time::PrimitiveDateTime, #[schema(value_type=String)] /// client secret pub secret: Secret<String>, } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for ClientSecretCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for ClientSecretResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v1")] /// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { /// customer_id to which this ephemeral key belongs to #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// time at which this ephemeral key was created pub created_at: i64, /// time at which this ephemeral key would expire pub expires: i64, /// ephemeral key pub secret: String, }
{ "crate": "api_models", "file": "crates/api_models/src/ephemeral_key.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_4504274048544726398
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/mandates.rs // Contains: 3 structs, 0 enums use common_types::payments as common_payments_types; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Default, Debug, Deserialize, Serialize)] pub struct MandateId { pub mandate_id: String, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema)] pub struct MandateRevokedResponse { /// The identifier for mandate pub mandate_id: String, /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, /// If there was an error while calling the connectors the code is received here #[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>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] pub struct MandateResponse { /// The identifier for mandate pub mandate_id: String, /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, /// The identifier for payment method pub payment_method_id: String, /// The payment method pub payment_method: String, /// The payment method type pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] pub struct MandateCardDetails { /// The last 4 digits of card pub last4_digits: Option<String>, /// The expiry month of card #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, /// The expiry year of card #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, /// The card holder name #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, /// The token from card locker #[schema(value_type = Option<String>)] pub card_token: Option<Secret<String>>, /// The card scheme network for the particular card pub scheme: Option<String>, /// The country code in in which the card was issued pub issuer_country: Option<String>, #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, /// The first 6 digits of card pub card_isin: Option<String>, /// The bank that issued the card pub card_issuer: Option<String>, /// The network that facilitates payment card transactions #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// The type of the payment card pub card_type: Option<String>, /// The nick_name of the card holder #[schema(value_type = Option<String>)] pub nick_name: Option<Secret<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MandateListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// offset on the number of objects to return pub offset: Option<i64>, /// status of the mandate pub mandate_status: Option<api_enums::MandateStatus>, /// connector linked to mandate pub connector: Option<String>, /// The time at which mandate is created #[schema(example = "2022-09-10T10:11:12Z")] pub created_time: Option<PrimitiveDateTime>, /// Time less than the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.lt")] pub created_time_lt: Option<PrimitiveDateTime>, /// Time greater than the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.gt")] pub created_time_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.lte")] pub created_time_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.gte")] pub created_time_gte: Option<PrimitiveDateTime>, } /// Details required for recurring payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RecurringDetails { MandateId(String), PaymentMethodId(String), ProcessorPaymentToken(ProcessorPaymentToken), /// Network transaction ID and Card Details for MIT payments when payment_method_data /// is not stored in the application NetworkTransactionIdAndCardDetails(NetworkTransactionIdAndCardDetails), } /// Processor payment token for MIT payments where payment_method_data is not available #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct ProcessorPaymentToken { pub processor_payment_token: String, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct NetworkTransactionIdAndCardDetails { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: cards::CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, /// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction), /// where `setup_future_usage` is set to `off_session`. #[schema(value_type = String)] pub network_transaction_id: Secret<String>, } impl RecurringDetails { pub fn is_network_transaction_id_and_card_details_flow(self) -> bool { matches!(self, Self::NetworkTransactionIdAndCardDetails(_)) } }
{ "crate": "api_models", "file": "crates/api_models/src/mandates.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_5124359559753056966
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/feature_matrix.rs // Contains: 5 structs, 1 enums use std::collections::HashSet; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct FeatureMatrixRequest { // List of connectors for which the feature matrix is requested #[schema(value_type = Option<Vec<Connector>>)] pub connectors: Option<Vec<common_enums::connector_enums::Connector>>, } #[derive(Debug, Clone, ToSchema, Serialize)] pub struct CardSpecificFeatures { /// Indicates whether three_ds card payments are supported #[schema(value_type = FeatureStatus)] pub three_ds: common_enums::FeatureStatus, /// Indicates whether non three_ds card payments are supported #[schema(value_type = FeatureStatus)] pub no_three_ds: common_enums::FeatureStatus, /// List of supported card networks #[schema(value_type = Vec<CardNetwork>)] pub supported_card_networks: Vec<common_enums::CardNetwork>, } #[derive(Debug, Clone, ToSchema, Serialize)] #[serde(untagged)] pub enum PaymentMethodSpecificFeatures { /// Card specific features Card(CardSpecificFeatures), } #[derive(Debug, ToSchema, Serialize)] pub struct SupportedPaymentMethod { /// The payment method supported by the connector #[schema(value_type = PaymentMethod)] pub payment_method: common_enums::PaymentMethod, /// The payment method type supported by the connector #[schema(value_type = PaymentMethodType)] pub payment_method_type: common_enums::PaymentMethodType, /// The display name of the payment method type pub payment_method_type_display_name: String, /// Indicates whether the payment method supports mandates via the connector #[schema(value_type = FeatureStatus)] pub mandates: common_enums::FeatureStatus, /// Indicates whether the payment method supports refunds via the connector #[schema(value_type = FeatureStatus)] pub refunds: common_enums::FeatureStatus, /// List of supported capture methods supported by the payment method type #[schema(value_type = Vec<CaptureMethod>)] pub supported_capture_methods: Vec<common_enums::CaptureMethod>, /// Information on the Payment method specific payment features #[serde(flatten)] pub payment_method_specific_features: Option<PaymentMethodSpecificFeatures>, /// List of countries supported by the payment method type via the connector #[schema(value_type = Option<HashSet<CountryAlpha3>>)] pub supported_countries: Option<HashSet<common_enums::CountryAlpha3>>, /// List of currencies supported by the payment method type via the connector #[schema(value_type = Option<HashSet<Currency>>)] pub supported_currencies: Option<HashSet<common_enums::Currency>>, } #[derive(Debug, ToSchema, Serialize)] pub struct ConnectorFeatureMatrixResponse { /// The name of the connector pub name: String, /// The display name of the connector pub display_name: String, /// The description of the connector pub description: String, /// The category of the connector #[schema(value_type = HyperswitchConnectorCategory, example = "payment_gateway")] pub category: common_enums::HyperswitchConnectorCategory, /// The integration status of the connector #[schema(value_type = ConnectorIntegrationStatus, example = "live")] pub integration_status: common_enums::ConnectorIntegrationStatus, /// The list of payment methods supported by the connector pub supported_payment_methods: Option<Vec<SupportedPaymentMethod>>, /// The list of webhook flows supported by the connector #[schema(value_type = Option<Vec<EventClass>>)] pub supported_webhook_flows: Option<Vec<common_enums::EventClass>>, } #[derive(Debug, Serialize, ToSchema)] pub struct FeatureMatrixListResponse { /// The number of connectors included in the response pub connector_count: usize, // The list of payments response objects pub connectors: Vec<ConnectorFeatureMatrixResponse>, } impl common_utils::events::ApiEventMetric for FeatureMatrixListResponse {} impl common_utils::events::ApiEventMetric for FeatureMatrixRequest {}
{ "crate": "api_models", "file": "crates/api_models/src/feature_matrix.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3399396692134431659
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/apple_pay_certificates_migration.rs // Contains: 2 structs, 0 enums #[derive(Debug, Clone, serde::Serialize)] pub struct ApplePayCertificatesMigrationResponse { pub migration_successful: Vec<common_utils::id_type::MerchantId>, pub migration_failed: Vec<common_utils::id_type::MerchantId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ApplePayCertificatesMigrationRequest { pub merchant_ids: Vec<common_utils::id_type::MerchantId>, } impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
{ "crate": "api_models", "file": "crates/api_models/src/apple_pay_certificates_migration.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_api_models_8645008171780518080
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/three_ds_decision_rule.rs // Contains: 7 structs, 0 enums use euclid::frontend::dir::enums::{ CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType, }; use utoipa::ToSchema; /// Represents the payment data used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentData { /// The amount of the payment in minor units (e.g., cents for USD). #[schema(value_type = i64)] pub amount: common_utils::types::MinorUnit, /// The currency of the payment. #[schema(value_type = Currency)] pub currency: common_enums::Currency, } /// Represents metadata about the payment method used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodMetaData { /// The card network (e.g., Visa, Mastercard) if the payment method is a card. #[schema(value_type = CardNetwork)] pub card_network: Option<common_enums::CardNetwork>, } /// Represents data about the customer's device used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CustomerDeviceData { /// The platform of the customer's device (e.g., Web, Android, iOS). pub platform: Option<CustomerDevicePlatform>, /// The type of the customer's device (e.g., Mobile, Tablet, Desktop). pub device_type: Option<CustomerDeviceType>, /// The display size of the customer's device. pub display_size: Option<CustomerDeviceDisplaySize>, } /// Represents data about the issuer used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IssuerData { /// The name of the issuer. pub name: Option<String>, /// The country of the issuer. #[schema(value_type = Country)] pub country: Option<common_enums::Country>, } /// Represents data about the acquirer used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AcquirerData { /// The country of the acquirer. #[schema(value_type = Country)] pub country: Option<common_enums::Country>, /// The fraud rate associated with the acquirer. pub fraud_rate: Option<f64>, } /// Represents the request to execute a 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ThreeDsDecisionRuleExecuteRequest { /// The ID of the routing algorithm to be executed. #[schema(value_type = String)] pub routing_id: common_utils::id_type::RoutingId, /// Data related to the payment. pub payment: PaymentData, /// Optional metadata about the payment method. pub payment_method: Option<PaymentMethodMetaData>, /// Optional data about the customer's device. pub customer_device: Option<CustomerDeviceData>, /// Optional data about the issuer. pub issuer: Option<IssuerData>, /// Optional data about the acquirer. pub acquirer: Option<AcquirerData>, } /// Represents the response from executing a 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThreeDsDecisionRuleExecuteResponse { /// The decision made by the 3DS decision rule engine. #[schema(value_type = ThreeDSDecision)] pub decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision, } impl common_utils::events::ApiEventMetric for ThreeDsDecisionRuleExecuteRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::ThreeDsDecisionRule) } } impl common_utils::events::ApiEventMetric for ThreeDsDecisionRuleExecuteResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::ThreeDsDecisionRule) } }
{ "crate": "api_models", "file": "crates/api_models/src/three_ds_decision_rule.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3929838080012975590
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/webhook_events.rs // Contains: 9 structs, 1 enums use std::collections::HashSet; use common_enums::{EventClass, EventType, WebhookDeliveryAttempt}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The constraints to apply when filtering events. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct EventListConstraints { /// Filter events created after the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_after: Option<PrimitiveDateTime>, /// Filter events created before the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_before: Option<PrimitiveDateTime>, /// Include at most the specified number of events. pub limit: Option<u16>, /// Include events after the specified offset. pub offset: Option<u16>, /// Filter all events associated with the specified object identifier (Payment Intent ID, /// Refund ID, etc.) pub object_id: Option<String>, /// Filter all events associated with the specified business profile ID. #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Filter events by their class. pub event_classes: Option<HashSet<EventClass>>, /// Filter events by their type. pub event_types: Option<HashSet<EventType>>, /// Filter all events by `is_overall_delivery_successful` field of the event. pub is_delivered: Option<bool>, } #[derive(Debug)] pub enum EventListConstraintsInternal { GenericFilter { created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, limit: Option<i64>, offset: Option<i64>, event_classes: Option<HashSet<EventClass>>, event_types: Option<HashSet<EventType>>, is_delivered: Option<bool>, }, ObjectIdFilter { object_id: String, }, } /// The response body for each item when listing events. #[derive(Debug, Serialize, ToSchema)] pub struct EventListItemResponse { /// The identifier for the Event. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub event_id: String, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the Business Profile. #[schema(max_length = 64, value_type = String, example = "SqB0zwDGR5wHppWf0bx7GKr1f2")] pub profile_id: common_utils::id_type::ProfileId, /// The identifier for the object (Payment Intent ID, Refund ID, etc.) #[schema(max_length = 64, example = "QHrfd5LUDdZaKtAjdJmMu0dMa1")] pub object_id: String, /// Specifies the type of event, which includes the object and its status. pub event_type: EventType, /// Specifies the class of event (the type of object: Payment, Refund, etc.) pub event_class: EventClass, /// Indicates whether the webhook was ultimately delivered or not. pub is_delivery_successful: Option<bool>, /// The identifier for the initial delivery attempt. This will be the same as `event_id` for /// the initial delivery attempt. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub initial_attempt_id: String, /// Time at which the event was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, } /// The response body of list initial delivery attempts api call. #[derive(Debug, Serialize, ToSchema)] pub struct TotalEventsResponse { /// The list of events pub events: Vec<EventListItemResponse>, /// Count of total events pub total_count: i64, } impl TotalEventsResponse { pub fn new(total_count: i64, events: Vec<EventListItemResponse>) -> Self { Self { events, total_count, } } } impl common_utils::events::ApiEventMetric for TotalEventsResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.events.first().map(|event| event.merchant_id.clone())?, }) } } /// The response body for retrieving an event. #[derive(Debug, Serialize, ToSchema)] pub struct EventRetrieveResponse { #[serde(flatten)] pub event_information: EventListItemResponse, /// The request information (headers and body) sent in the webhook. pub request: OutgoingWebhookRequestContent, /// The response information (headers, body and status code) received for the webhook sent. pub response: OutgoingWebhookResponseContent, /// Indicates the type of delivery attempt. pub delivery_attempt: Option<WebhookDeliveryAttempt>, } impl common_utils::events::ApiEventMetric for EventRetrieveResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.event_information.merchant_id.clone(), }) } } /// The request information (headers and body) sent in the webhook. #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct OutgoingWebhookRequestContent { /// The request body sent in the webhook. #[schema(value_type = String)] #[serde(alias = "payload")] pub body: Secret<String>, /// The request headers sent in the webhook. #[schema( value_type = Vec<(String, String)>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Vec<(String, Secret<String>)>, } /// The response information (headers, body and status code) received for the webhook sent. #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OutgoingWebhookResponseContent { /// The response body received for the webhook sent. #[schema(value_type = Option<String>)] #[serde(alias = "payload")] pub body: Option<Secret<String>>, /// The response headers received for the webhook sent. #[schema( value_type = Option<Vec<(String, String)>>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Option<Vec<(String, Secret<String>)>>, /// The HTTP status code for the webhook sent. #[schema(example = 200)] pub status_code: Option<u16>, /// Error message in case any error occurred when trying to deliver the webhook. #[schema(example = 200)] pub error_message: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct EventListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub constraints: EventListConstraints, } impl common_utils::events::ApiEventMetric for EventListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryAttemptListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub initial_attempt_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryAttemptListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryRetryRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub event_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryRetryRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } }
{ "crate": "api_models", "file": "crates/api_models/src/webhook_events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 9, "num_tables": null, "score": null, "total_crates": null }
file_api_models_8950506951033428791
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/relay.rs // Contains: 6 structs, 1 enums use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRequest { /// The identifier that is associated to a resource at the connector reference to which the relay request is being made #[schema(example = "7256228702616471803954")] pub connector_resource_id: String, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The type of relay request #[serde(rename = "type")] #[schema(value_type = RelayType)] pub relay_type: api_enums::RelayType, /// The data that is associated with the relay request pub data: Option<RelayData>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum RelayData { /// The data that is associated with a refund relay request Refund(RelayRefundRequestData), } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRefundRequestData { /// The amount that is being refunded #[schema(value_type = i64 , example = 6540)] pub amount: MinorUnit, /// The currency in which the amount is being refunded #[schema(value_type = Currency)] pub currency: api_enums::Currency, /// The reason for the refund #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayResponse { /// The unique identifier for the Relay #[schema(example = "relay_mbabizu24mvu3mela5njyhpit4", value_type = String)] pub id: common_utils::id_type::RelayId, /// The status of the relay request #[schema(value_type = RelayStatus)] pub status: api_enums::RelayStatus, /// The identifier that is associated to a resource at the connector reference to which the relay request is being made #[schema(example = "pi_3MKEivSFNglxLpam0ZaL98q9")] pub connector_resource_id: String, /// The error details if the relay request failed pub error: Option<RelayError>, /// The identifier that is associated to a resource at the connector to which the relay request is being made #[schema(example = "re_3QY4TnEOqOywnAIx1Mm1p7GQ")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The business profile that is associated with this relay request. #[schema(example = "pro_abcdefghijklmnopqrstuvwxyz", value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The type of relay request #[serde(rename = "type")] #[schema(value_type = RelayType)] pub relay_type: api_enums::RelayType, /// The data that is associated with the relay request pub data: Option<RelayData>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayError { /// The error code pub code: String, /// The error message pub message: String, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRetrieveRequest { /// The unique identifier for the Relay #[serde(default)] pub force_sync: bool, /// The unique identifier for the Relay pub id: common_utils::id_type::RelayId, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRetrieveBody { /// The unique identifier for the Relay #[serde(default)] pub force_sync: bool, } impl common_utils::events::ApiEventMetric for RelayRequest {} impl common_utils::events::ApiEventMetric for RelayResponse {} impl common_utils::events::ApiEventMetric for RelayRetrieveRequest {} impl common_utils::events::ApiEventMetric for RelayRetrieveBody {}
{ "crate": "api_models", "file": "crates/api_models/src/relay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_api_models_6095635398461428909
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/admin.rs // Contains: 64 structs, 6 enums use std::collections::{HashMap, HashSet}; use common_types::primitive_wrappers; use common_utils::{ consts, crypto::Encryptable, errors::{self, CustomResult}, ext_traits::Encode, id_type, link_utils, pii, }; #[cfg(feature = "v1")] use common_utils::{crypto::OptionalEncryptableName, ext_traits::ValueExt}; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use super::payments::AddressDetails; use crate::{ consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY}, enums as api_enums, payment_methods, }; #[cfg(feature = "v1")] use crate::{profile_acquirer::ProfileAcquirerResponse, routing}; #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantAccountListRequest { pub organization_id: id_type::OrganizationId, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountCreate { /// The identifier for the Merchant Account #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type= Option<String>,example = "NewAge Retailer")] pub merchant_name: Option<Secret<String>>, /// Details about the merchant, can contain phone and emails of primary and secondary contact person pub merchant_details: Option<MerchantDetails>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used for routing payments to desired connectors #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used for routing payouts to desired connectors #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled. #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<MerchantAccountMetadata>, /// API key that will be used for client side API access. A publishable key has to be always paired with a `client_secret`. /// A `client_secret` can be obtained by creating a payment with `confirm` set to false #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account #[schema(value_type = Option<PrimaryBusinessDetails>)] pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The id of the organization to which the merchant belongs to, if not passed an organization is created #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: Option<id_type::OrganizationId>, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, /// Merchant Account Type of this merchant account #[schema(value_type = Option<MerchantAccountRequestType>, example = "standard")] pub merchant_account_type: Option<api_enums::MerchantAccountRequestType>, } #[cfg(feature = "v1")] impl MerchantAccountCreate { pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { self.merchant_id.clone() } pub fn get_payment_response_hash_key(&self) -> Option<String> { self.payment_response_hash_key.clone().or(Some( common_utils::crypto::generate_cryptographically_secure_random_string(64), )) } pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { self.primary_business_details .clone() .unwrap_or_default() .encode_to_value() } pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { let _: routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("StaticRoutingAlgorithm")?; Ok(()) } None => Ok(()), } } // Get the enable payment response hash as a boolean, where the default value is true pub fn get_enable_payment_response_hash(&self) -> bool { self.enable_payment_response_hash.unwrap_or(true) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] #[schema(as = MerchantAccountCreate)] pub struct MerchantAccountCreateWithoutOrgId { /// Name of the Merchant Account, This will be used as a prefix to generate the id #[schema(value_type= String, max_length = 64, example = "NewAge Retailer")] pub merchant_name: Secret<common_utils::new_type::MerchantName>, /// Details about the merchant, contains phone and emails of primary and secondary contact person. pub merchant_details: Option<MerchantDetails>, /// Metadata is useful for storing additional, unstructured information about the merchant account. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } // In v2 the struct used in the API is MerchantAccountCreateWithoutOrgId // The following struct is only used internally, so we can reuse the common // part of `create_merchant_account` without duplicating its code for v2 #[cfg(feature = "v2")] #[derive(Clone, Debug, Serialize, ToSchema)] pub struct MerchantAccountCreate { pub merchant_name: Secret<common_utils::new_type::MerchantName>, pub merchant_details: Option<MerchantDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub organization_id: id_type::OrganizationId, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl MerchantAccountCreate { pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { id_type::MerchantId::from_merchant_name(self.merchant_name.clone().expose()) } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { Vec::<PrimaryBusinessDetails>::new().encode_to_value() } } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardTestingGuardConfig { /// Determines if Card IP Blocking is enabled for profile pub card_ip_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Card IP Blocking for profile pub card_ip_blocking_threshold: i32, /// Determines if Guest User Card Blocking is enabled for profile pub guest_user_card_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Guest User Card Blocking for profile pub guest_user_card_blocking_threshold: i32, /// Determines if Customer Id Blocking is enabled for profile pub customer_id_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Customer Id Blocking for profile pub customer_id_blocking_threshold: i32, /// Determines Redis Expiry for Card Testing Guard for profile pub card_testing_guard_expiry: i32, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardTestingGuardStatus { Enabled, Disabled, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AuthenticationConnectorDetails { /// List of authentication connectors #[schema(value_type = Vec<AuthenticationConnectors>)] pub authentication_connectors: Vec<common_enums::AuthenticationConnectors>, /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. 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>, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct ExternalVaultConnectorDetails { /// Merchant Connector id to be stored for vault connector #[schema(value_type = Option<String>)] pub vault_connector_id: id_type::MerchantConnectorAccountId, /// External vault to be used for storing payment method information #[schema(value_type = Option<VaultSdk>)] pub vault_sdk: Option<common_enums::VaultSdk>, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct MerchantAccountMetadata { pub compatible_connector: Option<api_enums::Connector>, #[serde(flatten)] pub data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(example = "NewAge Retailer")] pub merchant_name: Option<String>, /// Details about the merchant pub merchant_details: Option<MerchantDetails>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used for routing payments to desired connectors #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The default profile that must be used for creating merchant accounts and payments #[schema(max_length = 64, value_type = Option<String>)] pub default_profile: Option<id_type::ProfileId>, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, } #[cfg(feature = "v1")] impl MerchantAccountUpdate { pub fn get_primary_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.primary_business_details .as_ref() .map(|primary_business_details| primary_business_details.encode_to_value()) .transpose() } pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn get_webhook_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.webhook_details .as_ref() .map(|webhook_details| webhook_details.encode_to_value()) .transpose() } pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { let _: routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("StaticRoutingAlgorithm")?; Ok(()) } None => Ok(()), } } // Get the enable payment response hash as a boolean, where the default value is true pub fn get_enable_payment_response_hash(&self) -> bool { self.enable_payment_response_hash.unwrap_or(true) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { /// Name of the Merchant Account #[schema(example = "NewAge Retailer")] pub merchant_name: Option<String>, /// Details about the merchant pub merchant_details: Option<MerchantDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] impl MerchantAccountUpdate { pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = Option<String>,example = "NewAge Retailer")] pub merchant_name: OptionalEncryptableName, /// The URL to redirect after completion of the payment #[schema(max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<String>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")] pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Details about the merchant #[schema(value_type = Option<MerchantDetails>)] pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account #[schema(value_type = Vec<PrimaryBusinessDetails>)] pub primary_business_details: Vec<PrimaryBusinessDetails>, /// The frm routing algorithm to be used to process the incoming request from merchant to outgoing payment FRM. #[schema(value_type = Option<StaticRoutingAlgorithm>, max_length = 255, example = r#"{"type": "single", "data": "stripe" }"#)] pub frm_routing_algorithm: Option<serde_json::Value>, /// The organization id merchant is associated with #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false pub is_recon_enabled: bool, /// The default profile that must be used for creating merchant accounts and payments #[schema(max_length = 64, value_type = Option<String>)] pub default_profile: Option<id_type::ProfileId>, /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, /// Merchant Account Type of this merchant account #[schema(value_type = MerchantAccountType, example = "standard")] pub merchant_account_type: api_enums::MerchantAccountType, } #[cfg(feature = "v2")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = String,example = "NewAge Retailer")] pub merchant_name: Secret<String>, /// Details about the merchant #[schema(value_type = Option<MerchantDetails>)] pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: String, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The id of the organization which the merchant is associated with #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantDetails { /// The merchant's primary contact name #[schema(value_type = Option<String>, max_length = 255, example = "John Doe")] pub primary_contact_person: Option<Secret<String>>, /// The merchant's primary phone number #[schema(value_type = Option<String>, max_length = 255, example = "999999999")] pub primary_phone: Option<Secret<String>>, /// The merchant's primary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe@test.com")] pub primary_email: Option<pii::Email>, /// The merchant's secondary contact name #[schema(value_type = Option<String>, max_length= 255, example = "John Doe2")] pub secondary_contact_person: Option<Secret<String>>, /// The merchant's secondary phone number #[schema(value_type = Option<String>, max_length = 255, example = "999999988")] pub secondary_phone: Option<Secret<String>>, /// The merchant's secondary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe2@test.com")] pub secondary_email: Option<pii::Email>, /// The business website of the merchant #[schema(max_length = 255, example = "www.example.com")] pub website: Option<String>, /// A brief description about merchant's business #[schema( max_length = 255, example = "Online Retail with a wide selection of organic products for North America" )] pub about_business: Option<String>, /// The merchant's address details pub address: Option<AddressDetails>, #[schema(value_type = Option<String>, example = "123456789")] pub merchant_tax_registration_id: Option<Secret<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct PrimaryBusinessDetails { #[schema(value_type = CountryAlpha2)] pub country: api_enums::CountryAlpha2, #[schema(example = "food")] pub business: String, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct WebhookDetails { ///The version for Webhook #[schema(max_length = 255, max_length = 255, example = "1.0.2")] pub webhook_version: Option<String>, ///The user name for Webhook login #[schema(max_length = 255, max_length = 255, example = "ekart_retail")] pub webhook_username: Option<String>, ///The password for Webhook login #[schema(value_type = Option<String>, max_length = 255, example = "ekart@123")] pub webhook_password: Option<Secret<String>>, ///The url for the webhook endpoint #[schema(value_type = Option<String>, example = "www.ekart.com/webhooks")] pub webhook_url: Option<Secret<String>>, /// If this property is true, a webhook message is posted whenever a new payment is created #[schema(example = true)] pub payment_created_enabled: Option<bool>, /// If this property is true, a webhook message is posted whenever a payment is successful #[schema(example = true)] pub payment_succeeded_enabled: Option<bool>, /// If this property is true, a webhook message is posted whenever a payment fails #[schema(example = true)] pub payment_failed_enabled: Option<bool>, /// List of payment statuses that triggers a webhook for payment intents #[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))] pub payment_statuses_enabled: Option<Vec<api_enums::IntentStatus>>, /// List of refund statuses that triggers a webhook for refunds #[schema(value_type = Vec<IntentStatus>, example = json!(["success", "failure"]))] pub refund_statuses_enabled: Option<Vec<api_enums::RefundStatus>>, /// List of payout statuses that triggers a webhook for payouts #[cfg(feature = "payouts")] #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))] pub payout_statuses_enabled: Option<Vec<api_enums::PayoutStatus>>, } impl WebhookDetails { fn validate_statuses<T>(statuses: &[T], status_type_name: &str) -> Result<(), String> where T: strum::IntoEnumIterator + Copy + PartialEq + std::fmt::Debug, T: Into<Option<api_enums::EventType>>, { let valid_statuses: Vec<T> = T::iter().filter(|s| (*s).into().is_some()).collect(); for status in statuses { if !valid_statuses.contains(status) { return Err(format!( "Invalid {status_type_name} webhook status provided: {status:?}" )); } } Ok(()) } pub fn validate(&self) -> Result<(), String> { if let Some(payment_statuses) = &self.payment_statuses_enabled { Self::validate_statuses(payment_statuses, "payment")?; } if let Some(refund_statuses) = &self.refund_statuses_enabled { Self::validate_statuses(refund_statuses, "refund")?; } #[cfg(feature = "payouts")] { if let Some(payout_statuses) = &self.payout_statuses_enabled { Self::validate_statuses(payout_statuses, "payout")?; } } Ok(()) } } #[derive(Debug, Serialize, ToSchema)] pub struct MerchantAccountDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[derive(Default, Debug, Deserialize, Serialize)] pub struct MerchantId { pub merchant_id: id_type::MerchantId, } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantConnectorId { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantConnectorId { #[schema(value_type = String)] pub id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorCreate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: api_enums::Connector, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = PaymentMethodsEnabled)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<ConnectorStatus>, example = "inactive")] // By default the ConnectorStatus is Active pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorCreate { pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } pub fn get_connector_label(&self, profile_name: String) -> String { match self.connector_label.clone() { Some(connector_label) => connector_label, None => format!("{}_{}", self.connector_name, profile_name), } } } #[cfg(feature = "v1")] /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorCreate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: api_enums::Connector, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead pub business_label: Option<String>, /// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "chase")] pub business_sub_label: Option<String>, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<ConnectorStatus>, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] impl MerchantConnectorCreate { pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum AdditionalMerchantData { OpenBankingRecipientData(MerchantRecipientData), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] /// Feature metadata for merchant connector account pub struct MerchantConnectorAccountFeatureMetadata { /// Revenue recovery metadata for merchant connector account pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] /// Revenue recovery metadata for merchant connector account pub struct RevenueRecoveryMetadata { /// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`. Once this limit is reached, no further retries will be attempted. #[schema(value_type = u16, example = "15")] pub max_retry_count: u16, /// Maximum number of `billing connector` retries before revenue recovery can start executing retries. #[schema(value_type = u16, example = "10")] pub billing_connector_retry_threshold: u16, /// Billing account reference id is payment gateway id at billing connector end. /// Merchants need to provide a mapping between these merchant connector account and the corresponding account reference IDs for each `billing connector`. #[schema(value_type = u16, example = r#"{ "mca_vDSg5z6AxnisHq5dbJ6g": "stripe_123", "mca_vDSg5z6AumisHqh4x5m1": "adyen_123" }"#)] pub billing_account_reference: HashMap<id_type::MerchantConnectorAccountId, String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MerchantAccountData { /// IBAN-based account for international transfers Iban { /// International Bank Account Number (up to 34 characters) #[schema(value_type = String)] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// UK BACS payment system Bacs { /// 8-digit UK account number #[schema(value_type = String)] account_number: Secret<String>, /// 6-digit UK sort code #[schema(value_type = String, example = "123456")] sort_code: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// UK Faster Payments (instant transfers) FasterPayments { /// 8-digit UK account number #[schema(value_type = String)] account_number: Secret<String>, /// 6-digit UK sort code #[schema(value_type = String)] sort_code: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// SEPA payments (Euro zone) Sepa { /// IBAN for SEPA transfers #[schema(value_type = String, example = "FR1420041010050500013M02606")] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// SEPA Instant payments (10-second transfers) SepaInstant { /// IBAN for instant SEPA transfers #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// Polish Elixir payment system Elixir { /// Polish account number (26 digits) #[schema(value_type = String, example = "12345678901234567890123456")] account_number: Secret<String>, /// Polish IBAN (28 chars) #[schema(value_type = String, example = "PL27114020040000300201355387")] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// Swedish Bankgiro system Bankgiro { /// Bankgiro number (7-8 digits) #[schema(value_type = String, example = "5402-9656")] number: Secret<String>, /// Account holder name #[schema(example = "Erik Andersson")] name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// Swedish Plusgiro system Plusgiro { /// Plusgiro number (2-8 digits) #[schema(value_type = String, example = "4789-2")] number: Secret<String>, /// Account holder name #[schema(example = "Anna Larsson")] name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { #[schema(value_type= Option<String>)] ConnectorRecipientId(Secret<String>), #[schema(value_type= Option<String>)] WalletId(Secret<String>), AccountData(MerchantAccountData), } // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { TemporaryAuth, HeaderKey { api_key: Secret<String>, }, BodyKey { api_key: Secret<String>, key1: Secret<String>, }, SignatureKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, }, MultiAuthKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, key2: Secret<String>, }, CurrencyAuthKey { auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>, }, CertificateAuth { // certificate should be base64 encoded certificate: Secret<String>, // private_key should be base64 encoded private_key: Secret<String>, }, #[default] NoKey, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorWebhookDetails { #[schema(value_type = String, example = "12345678900987654321")] pub merchant_secret: Secret<String>, #[schema(value_type = String, example = "12345678900987654321")] pub additional_secret: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorInfo { pub connector_label: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } impl MerchantConnectorInfo { pub fn new( connector_label: String, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> Self { Self { connector_label, merchant_connector_id, } } } /// Response of creating a new Merchant Connector for the merchant account." #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: common_enums::connector_enums::Connector, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Vec<PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } } /// Response of creating a new Merchant Connector for the merchant account." #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: String, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, ///The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "travel")] pub business_label: Option<String>, /// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "chase")] pub business_sub_label: Option<String>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] impl MerchantConnectorResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorListResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: String, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, ///The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "travel")] pub business_label: Option<String>, /// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "chase")] pub business_sub_label: Option<String>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, } #[cfg(feature = "v1")] impl MerchantConnectorListResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } pub fn get_connector_name(&self) -> String { self.connector_name.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorListResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: common_enums::connector_enums::Connector, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Vec<PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, } #[cfg(feature = "v2")] impl MerchantConnectorListResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector { self.connector_name } } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorUpdate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ConnectorWalletDetails { /// This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub apple_pay_combined: Option<pii::SecretSerdeValue>, /// This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub apple_pay: Option<pii::SecretSerdeValue>, /// This field contains the Amazon Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub amazon_pay: Option<pii::SecretSerdeValue>, /// This field contains the Samsung Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub samsung_pay: Option<pii::SecretSerdeValue>, /// This field contains the Paze certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub paze: Option<pii::SecretSerdeValue>, /// This field contains the Google Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub google_pay: Option<pii::SecretSerdeValue>, } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorUpdate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Option<Vec<PaymentMethodsEnabled>>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// 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>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// The identifier for the Merchant Account #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_id: id_type::MerchantId, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorUpdate { pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } } ///Details of FrmConfigs are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmConfigs { ///this is the connector that can be used for the payment #[schema(value_type = ConnectorType, example = "payment_processor")] pub gateway: Option<api_enums::Connector>, ///payment methods that can be used in the payment pub payment_methods: Vec<FrmPaymentMethod>, } ///Details of FrmPaymentMethod are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmPaymentMethod { ///payment methods(card, wallet, etc) that can be used in the payment #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: Option<common_enums::PaymentMethod>, ///payment method types(credit, debit) that can be used in the payment. This field is deprecated. It has not been removed to provide backward compatibility. pub payment_method_types: Option<Vec<FrmPaymentMethodType>>, ///frm flow type to be used, can be pre/post #[schema(value_type = Option<FrmPreferredFlowTypes>)] pub flow: Option<api_enums::FrmPreferredFlowTypes>, } ///Details of FrmPaymentMethodType are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmPaymentMethodType { ///payment method types(credit, debit) that can be used in the payment #[schema(value_type = PaymentMethodType)] pub payment_method_type: Option<common_enums::PaymentMethodType>, ///card networks(like visa mastercard) types that can be used in the payment #[schema(value_type = CardNetwork)] pub card_networks: Option<Vec<common_enums::CardNetwork>>, ///frm flow type to be used, can be pre/post #[schema(value_type = FrmPreferredFlowTypes)] pub flow: api_enums::FrmPreferredFlowTypes, ///action that the frm would take, in case fraud is detected #[schema(value_type = FrmAction)] pub action: api_enums::FrmAction, } /// Details of all the payment methods enabled for the connector for the given merchant account #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodsEnabled { /// Type of payment method. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: common_enums::PaymentMethod, /// Subtype of payment method #[schema(value_type = Option<Vec<RequestPaymentMethodTypes>>,example = json!(["credit"]))] pub payment_method_types: Option<Vec<payment_methods::RequestPaymentMethodTypes>>, } impl PaymentMethodsEnabled { /// Get payment_method #[cfg(feature = "v1")] pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { Some(self.payment_method) } /// Get payment_method_types #[cfg(feature = "v1")] pub fn get_payment_method_type( &self, ) -> Option<&Vec<payment_methods::RequestPaymentMethodTypes>> { self.payment_method_types.as_ref() } } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] pub enum AcceptedCurrencies { #[schema(value_type = Vec<Currency>)] EnableOnly(Vec<api_enums::Currency>), #[schema(value_type = Vec<Currency>)] DisableOnly(Vec<api_enums::Currency>), AllAccepted, } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] /// Object to filter the customer countries for which the payment method is displayed pub enum AcceptedCountries { #[schema(value_type = Vec<CountryAlpha2>)] EnableOnly(Vec<api_enums::CountryAlpha2>), #[schema(value_type = Vec<CountryAlpha2>)] DisableOnly(Vec<api_enums::CountryAlpha2>), AllAccepted, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MerchantKeyTransferRequest { /// Offset for merchant account #[schema(example = 32)] pub from: u32, /// Limit for merchant account #[schema(example = 32)] pub limit: u32, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct TransferKeyResponse { /// The identifier for the Merchant Account #[schema(example = 32)] pub total_transferred: usize, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVRequest { #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleAllKVRequest { /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleAllKVResponse { ///Total number of updated merchants #[schema(example = 20)] pub total_updated: usize, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } /// Merchant connector details used to make payments. #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MerchantConnectorDetailsWrap { /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info, like encoded_data in this field. And do not send the string "null". pub creds_identifier: String, /// Merchant connector details type type. Base64 Encode the credentials and send it in this type and send as a string. #[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{ "connector_account_details": { "auth_type": "HeaderKey", "api_key":"sk_test_xxxxxexamplexxxxxx12345" }, "metadata": { "user_defined_field_1": "sample_1", "user_defined_field_2": "sample_2", }, }"#)] pub encoded_data: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] pub struct MerchantConnectorDetails { /// Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if pre network tokenization is enabled or not pub is_pre_network_tokenization_enabled: Option<bool>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Time interval (in hours) for polling the connector to check for new disputes #[schema(value_type = Option<i32>, example = 2)] pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, /// Indicates if manual retry for payment is enabled or not pub is_manual_retry_enabled: Option<bool>, /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, /// Indicates if external vault is enabled or not. #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[nutype::nutype( validate(greater_or_equal = MIN_ORDER_FULFILLMENT_EXPIRY, less_or_equal = MAX_ORDER_FULFILLMENT_EXPIRY), derive(Clone, Copy, Debug, Deserialize, Serialize) )] pub struct OrderFulfillmentTime(i64); #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if external vault is enabled or not. pub is_external_vault_enabled: Option<bool>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct ProfileResponse { /// The identifier for Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for profile. This must be used for creating merchant accounts, payments and payouts #[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")] pub profile_id: id_type::ProfileId, /// Name of the profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<String>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<i64>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<i64>, /// Default Payment Link config for all payment links created under this profile #[schema(value_type = Option<BusinessPaymentLinkConfig>)] pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[schema(default = false, example = false)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. #[schema(default = false, example = false)] pub is_auto_retries_enabled: bool, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<i16>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: bool, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: bool, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if pre network tokenization is enabled or not #[schema(default = false, example = false)] pub is_pre_network_tokenization_enabled: bool, /// Acquirer configs #[schema(value_type = Option<Vec<ProfileAcquirerResponse>>)] pub acquirer_configs: Option<Vec<ProfileAcquirerResponse>>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Time interval (in hours) for polling the connector to check dispute statuses #[schema(value_type = Option<u32>, example = 2)] pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, /// Indicates if manual retry for payment is enabled or not pub is_manual_retry_enabled: Option<bool>, /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, /// Indicates if external vault is enabled or not. #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct ProfileResponse { /// The identifier for Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for profile. This must be used for creating merchant accounts, payments and payouts #[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")] pub id: id_type::ProfileId, /// Name of the profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<i64>, /// Default Payment Link config for all payment links created under this profile #[schema(value_type = Option<BusinessPaymentLinkConfig>)] pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[schema(default = false, example = false)] pub is_network_tokenization_enabled: bool, /// Indicates if CVV should be collected during payment or not. #[schema(value_type = Option<bool>)] pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: bool, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if external vault is enabled or not. pub is_external_vault_enabled: Option<bool>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// 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, /// Indicates the state of revenue recovery algorithm type #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileUpdate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: Option<bool>, /// Indicates if dynamic routing is enabled or not. #[serde(default)] pub dynamic_routing_algorithm: Option<serde_json::Value>, /// Indicates if network tokenization is enabled or not. pub is_network_tokenization_enabled: Option<bool>, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: Option<bool>, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if pre network tokenization is enabled or not #[schema(default = false, example = false)] pub is_pre_network_tokenization_enabled: Option<bool>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Time interval (in hours) for polling the connector to check for new disputes #[schema(value_type = Option<u32>, example = 2)] pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, /// Indicates if manual retry for payment is enabled or not pub is_manual_retry_enabled: Option<bool>, /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, /// Indicates if external vault is enabled or not. #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileUpdate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: Option<bool>, /// Indicates if network tokenization is enabled or not. pub is_network_tokenization_enabled: Option<bool>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: Option<bool>, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if external vault is enabled or not. pub is_external_vault_enabled: Option<bool>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Indicates the state of revenue recovery algorithm type #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessCollectLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, /// List of payment methods shown on collect UI #[schema(value_type = Vec<EnabledPaymentMethod>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs", "sepa"]}]"#)] pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// Allows for removing any validations / pre-requisites which are necessary in a production environment #[schema(value_type = Option<bool>, default = false)] pub payout_test_mode: Option<bool>, } #[derive(Clone, Debug, serde::Serialize)] pub struct MaskedHeaders(HashMap<String, String>); impl MaskedHeaders { fn mask_value(value: &str) -> String { let value_len = value.len(); let masked_value = if value_len <= 4 { "*".repeat(value_len) } else { value .char_indices() .map(|(index, ch)| { if index < 2 || index >= value_len - 2 { // Show the first two and last two characters, mask the rest with '*' ch } else { // Mask the remaining characters '*' } }) .collect::<String>() }; masked_value } pub fn from_headers(headers: HashMap<String, Secret<String>>) -> Self { let masked_headers = headers .into_iter() .map(|(key, value)| (key, Self::mask_value(value.peek()))) .collect(); Self(masked_headers) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessGenericLinkConfig { /// Custom domain name to be used for hosting the link pub domain_name: Option<String>, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: HashSet<String>, #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, } impl BusinessGenericLinkConfig { pub fn validate(&self) -> Result<(), &str> { // Validate host domain name let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payout_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payout_link_config"); } Ok(()) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct BusinessPaymentLinkConfig { /// Custom domain name to be used for hosting the link in your own domain pub domain_name: Option<String>, /// Default payment link config for all future payment link #[serde(flatten)] #[schema(value_type = PaymentLinkConfigRequest)] pub default_config: Option<PaymentLinkConfigRequest>, /// list of configs for multi theme setup pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from #[schema(value_type = Option<HashSet<String>>)] pub allowed_domains: Option<HashSet<String>>, /// Toggle for HyperSwitch branding visibility pub branding_visibility: Option<bool>, } impl BusinessPaymentLinkConfig { pub fn validate(&self) -> Result<(), &str> { let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payment_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .map(|allowed_domains| { allowed_domains .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)) }) .unwrap_or(true); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payment_link_config"); } Ok(()) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkConfigRequest { /// custom theme for the payment link #[schema(value_type = Option<String>, max_length = 255, example = "#4E6ADD")] pub theme: Option<String>, /// merchant display logo #[schema(value_type = Option<String>, max_length = 255, example = "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg")] pub logo: Option<String>, /// Custom merchant name for payment link #[schema(value_type = Option<String>, max_length = 255, example = "hyperswitch")] pub seller_name: Option<String>, /// Custom layout for sdk #[schema(value_type = Option<String>, max_length = 255, example = "accordion")] pub sdk_layout: Option<String>, /// Display only the sdk for payment link #[schema(default = false, example = true)] pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link #[schema(default = false, example = true)] pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link #[schema(default = false, example = true)] pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link #[schema(default = true, example = true)] pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")] pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, /// Optional header for the SDK's payment form pub payment_form_header_text: Option<String>, /// Label type in the SDK's payment form #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, /// Boolean for controlling whether or not to show the explicit consent for storing cards #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, /// Hex color for the CVC icon during error state pub color_icon_card_cvc_error: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details #[schema(value_type = String, max_length = 255, example = "Policy-Number")] pub key: String, /// Value for the transaction details #[schema(value_type = String, max_length = 255, example = "297472368473924")] pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI #[schema(value_type = Option<i8>, example = 5)] pub position: Option<i8>, /// Whether the key should be bold #[schema(default = false, example = true)] pub is_key_bold: Option<bool>, /// Whether the value should be bold #[schema(default = false, example = true)] pub is_value_bold: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkBackgroundImageConfig { /// URL of the image #[schema(value_type = String, example = "https://hyperswitch.io/favicon.ico")] pub url: common_utils::types::Url, /// Position of the image in the UI #[schema(value_type = Option<ElementPosition>, example = "top-left")] pub position: Option<api_enums::ElementPosition>, /// Size of the image in the UI #[schema(value_type = Option<ElementSize>, example = "contain")] pub size: Option<api_enums::ElementSize>, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] pub struct PaymentLinkConfig { /// custom theme for the payment link pub theme: String, /// merchant display logo pub logo: String, /// Custom merchant name for payment link pub seller_name: String, /// Custom layout for sdk pub sdk_layout: String, /// Display only the sdk for payment link pub display_sdk_only: bool, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: bool, /// Hide card nickname field option for payment link pub hide_card_nickname_field: bool, /// Show card form by default for payment link pub show_card_form_by_default: bool, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: Option<HashSet<String>>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")] pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, /// Toggle for HyperSwitch branding visibility pub branding_visibility: Option<bool>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: bool, /// Optional header for the SDK's payment form pub payment_form_header_text: Option<String>, /// Label type in the SDK's payment form #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, /// Boolean for controlling whether or not to show the explicit consent for storing cards #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, /// Hex color for the CVC icon during error state pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ExtendedCardInfoChoice { pub enabled: bool, } impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ConnectorAgnosticMitChoice { pub enabled: bool, } impl common_utils::events::ApiEventMetric for ConnectorAgnosticMitChoice {} impl common_utils::events::ApiEventMetric for payment_methods::PaymentMethodMigrate {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ExtendedCardInfoConfig { /// Merchant public key #[schema(value_type = String)] pub public_key: Secret<String>, /// TTL for extended card info #[schema(default = 900, maximum = 7200, value_type = u16)] #[serde(default)] pub ttl_in_secs: TtlForExtendedCardInfo, } #[derive(Debug, serde::Serialize, Clone)] pub struct TtlForExtendedCardInfo(u16); impl Default for TtlForExtendedCardInfo { fn default() -> Self { Self(consts::DEFAULT_TTL_FOR_EXTENDED_CARD_INFO) } } impl<'de> Deserialize<'de> for TtlForExtendedCardInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = u16::deserialize(deserializer)?; // Check if value exceeds the maximum allowed if value > consts::MAX_TTL_FOR_EXTENDED_CARD_INFO { Err(serde::de::Error::custom( "ttl_in_secs must be less than or equal to 7200 (2hrs)", )) } else { Ok(Self(value)) } } } impl std::ops::Deref for TtlForExtendedCardInfo { type Target = u16; fn deref(&self) -> &Self::Target { &self.0 } }
{ "crate": "api_models", "file": "crates/api_models/src/admin.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 6, "num_structs": 64, "num_tables": null, "score": null, "total_crates": null }
file_api_models_45026368221768515
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/connector_onboarding.rs // Contains: 6 structs, 3 enums use common_utils::id_type; use super::{admin, enums}; #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct ActionUrlRequest { pub connector: enums::Connector, pub connector_id: id_type::MerchantConnectorAccountId, pub return_url: String, } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "lowercase")] pub enum ActionUrlResponse { PayPal(PayPalActionUrlResponse), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct OnboardingSyncRequest { pub profile_id: id_type::ProfileId, pub connector_id: id_type::MerchantConnectorAccountId, pub connector: enums::Connector, } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalActionUrlResponse { pub action_url: String, } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "lowercase")] pub enum OnboardingStatus { PayPal(PayPalOnboardingStatus), } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "snake_case")] pub enum PayPalOnboardingStatus { AccountNotFound, PaymentsNotReceivable, PpcpCustomDenied, MorePermissionsNeeded, EmailNotVerified, Success(PayPalOnboardingDone), ConnectorIntegrated(Box<admin::MerchantConnectorResponse>), } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalOnboardingDone { pub payer_id: id_type::MerchantId, } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalIntegrationDone { pub connector_id: String, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct ResetTrackingIdRequest { pub connector_id: id_type::MerchantConnectorAccountId, pub connector: enums::Connector, }
{ "crate": "api_models", "file": "crates/api_models/src/connector_onboarding.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_api_models_4755030169067386851
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/chat.rs // Contains: 5 structs, 0 enums use common_utils::id_type; use masking::Secret; use time::PrimitiveDateTime; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatRequest { pub message: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatResponse { pub response: Secret<serde_json::Value>, pub merchant_id: id_type::MerchantId, pub status: String, #[serde(skip_serializing)] pub query_executed: Option<Secret<String>>, #[serde(skip_serializing)] pub row_count: Option<i32>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ChatListRequest { pub merchant_id: Option<id_type::MerchantId>, pub limit: Option<i64>, pub offset: Option<i64>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ChatConversation { pub id: String, pub session_id: Option<String>, pub user_id: Option<String>, pub merchant_id: Option<String>, pub profile_id: Option<String>, pub org_id: Option<String>, pub role_id: Option<String>, pub user_query: Secret<String>, pub response: Secret<serde_json::Value>, pub database_query: Option<String>, pub interaction_status: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ChatListResponse { pub conversations: Vec<ChatConversation>, }
{ "crate": "api_models", "file": "crates/api_models/src/chat.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_2036196632409030567
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/pm_auth.rs // Contains: 6 structs, 0 enums use common_enums::{PaymentMethod, PaymentMethodType}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, id_type, impl_api_event_type, }; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct LinkTokenCreateRequest { pub language: Option<String>, // optional language field to be passed pub client_secret: Option<String>, // client secret to be passed in req body pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector } #[derive(Debug, Clone, serde::Serialize)] pub struct LinkTokenCreateResponse { pub link_token: String, // link_token received in response pub connector: String, // pm_auth connector name in response } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct ExchangeTokenCreateRequest { pub public_token: String, pub client_secret: Option<String>, pub payment_id: id_type::PaymentId, pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, } #[derive(Debug, Clone, serde::Serialize)] pub struct ExchangeTokenCreateResponse { pub access_token: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodAuthConfig { pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodAuthConnectorChoice { pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, pub connector_name: String, pub mca_id: id_type::MerchantConnectorAccountId, } impl_api_event_type!( Miscellaneous, ( LinkTokenCreateRequest, LinkTokenCreateResponse, ExchangeTokenCreateRequest, ExchangeTokenCreateResponse ) );
{ "crate": "api_models", "file": "crates/api_models/src/pm_auth.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-2598883250609453721
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/payments/additional_info.rs // Contains: 13 structs, 5 enums use common_utils::new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; use masking::Secret; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankDebitAdditionalData { Ach(Box<AchBankDebitAdditionalData>), Bacs(Box<BacsBankDebitAdditionalData>), Becs(Box<BecsBankDebitAdditionalData>), Sepa(Box<SepaBankDebitAdditionalData>), SepaGuarenteedDebit(Box<SepaBankDebitAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBankDebitAdditionalData { /// Partially masked account number for ach bank debit payment #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked routing number for ach bank debit payment #[schema(value_type = String, example = "110***000")] pub routing_number: MaskedRoutingNumber, /// Card holder's name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, /// Name of the bank #[schema(value_type = Option<BankNames>, example = "ach")] pub bank_name: Option<common_enums::BankNames>, /// Bank account type #[schema(value_type = Option<BankType>, example = "checking")] pub bank_type: Option<common_enums::BankType>, /// Bank holder entity type #[schema(value_type = Option<BankHolderType>, example = "personal")] pub bank_holder_type: Option<common_enums::BankHolderType>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankDebitAdditionalData { /// Partially masked account number for Bacs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked sort code for Bacs payment method #[schema(value_type = String, example = "108800")] pub sort_code: MaskedSortCode, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BecsBankDebitAdditionalData { /// Partially masked account number for Becs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] pub bsb_number: Secret<String>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankDebitAdditionalData { /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = String, example = "DE8937******013000")] pub iban: MaskedIban, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub enum BankRedirectDetails { BancontactCard(Box<BancontactBankRedirectAdditionalData>), Blik(Box<BlikBankRedirectAdditionalData>), Giropay(Box<GiropayBankRedirectAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BancontactBankRedirectAdditionalData { /// Last 4 digits of the card number #[schema(value_type = Option<String>, example = "4242")] pub last4: Option<String>, /// The card's expiry month #[schema(value_type = Option<String>, example = "12")] pub card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = Option<String>, example = "24")] pub card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = Option<String>, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BlikBankRedirectAdditionalData { #[schema(value_type = Option<String>, example = "3GD9MO")] pub blik_code: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GiropayBankRedirectAdditionalData { #[schema(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>)] pub iban: Option<MaskedIban>, /// Country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferAdditionalData { Ach {}, Sepa {}, Bacs {}, Multibanco {}, Permata {}, Bca {}, BniVa {}, BriVa {}, CimbVa {}, DanamonVa {}, MandiriVa {}, Pix(Box<PixBankTransferAdditionalData>), Pse {}, LocalBankTransfer(Box<LocalBankTransferAdditionalData>), InstantBankTransfer {}, InstantBankTransferFinland {}, InstantBankTransferPoland {}, IndonesianBankTransfer { #[schema(value_type = Option<BankNames>, example = "bri")] bank_name: Option<common_enums::BankNames>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PixBankTransferAdditionalData { /// Partially masked unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e ****** 6fa48899c1d1")] pub pix_key: Option<MaskedBankAccount>, /// Partially masked CPF - CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "**** 124689")] pub cpf: Option<MaskedBankAccount>, /// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "**** 417312")] pub cnpj: Option<MaskedBankAccount>, /// Partially masked source bank account number #[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")] 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)] 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")] pub expiry_date: Option<time::PrimitiveDateTime>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct LocalBankTransferAdditionalData { /// Partially masked bank code #[schema(value_type = Option<String>, example = "**** OA2312")] pub bank_code: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum GiftCardAdditionalData { Givex(Box<GivexGiftCardAdditionalData>), PaySafeCard {}, BhnCardNetwork {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GivexGiftCardAdditionalData { /// Last 4 digits of the gift card number #[schema(value_type = String, example = "4242")] pub last4: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardTokenAdditionalData { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiAdditionalData { UpiCollect(Box<UpiCollectAdditionalData>), #[schema(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)] pub struct UpiCollectAdditionalData { /// Masked VPA ID #[schema(value_type = Option<String>, example = "ab********@okhdfcbank")] pub vpa_id: Option<MaskedUpiVpaId>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WalletAdditionalDataForCard { /// Last 4 digits of the card number pub last4: String, /// The information of the payment method pub card_network: String, /// The type of payment method #[serde(rename = "type")] pub card_type: Option<String>, }
{ "crate": "api_models", "file": "crates/api_models/src/payments/additional_info.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 5, "num_structs": 13, "num_tables": null, "score": null, "total_crates": null }
file_api_models_1659797778319824644
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/process_tracker/revenue_recovery.rs // Contains: 3 structs, 0 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/process_tracker/revenue_recovery.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-5089550351639442742
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user_role/role.rs // Contains: 16 structs, 2 enums 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>, }
{ "crate": "api_models", "file": "crates/api_models/src/user_role/role.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 16, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3041898420075425125
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user/theme.rs // Contains: 18 structs, 0 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/user/theme.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 18, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-2464613687927090185
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user/dashboard_metadata.rs // Contains: 12 structs, 4 enums 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>), }
{ "crate": "api_models", "file": "crates/api_models/src/user/dashboard_metadata.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 12, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-7615689190717268015
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user/sample_data.rs // Contains: 1 structs, 0 enums 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>, }
{ "crate": "api_models", "file": "crates/api_models/src/user/sample_data.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_1508087544706207867
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/errors/types.rs // Contains: 3 structs, 2 enums 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>, #[cfg(feature = "detailed_errors")] pub stacktrace: Option<serde_json::Value>, } 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, #[cfg(feature = "detailed_errors")] stacktrace: None, } } } #[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>, #[cfg(feature = "detailed_errors")] #[serde(skip_serializing_if = "Option::is_none")] pub stacktrace: Option<serde_json::Value>, } 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(), #[cfg(feature = "detailed_errors")] stacktrace: error_info.stacktrace.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 {}
{ "crate": "api_models", "file": "crates/api_models/src/errors/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-3992067522859529480
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/payment_intents.rs // Contains: 5 structs, 2 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/payment_intents.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_8171058890446266390
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/api_event.rs // Contains: 5 structs, 3 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/api_event.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-1608730142656652900
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/outgoing_webhook_event.rs // Contains: 1 structs, 0 enums #[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>, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/outgoing_webhook_event.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_302061563789180145
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/refunds.rs // Contains: 6 structs, 4 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/refunds.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-3685019693585364810
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/payments.rs // Contains: 5 structs, 3 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/payments.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-3968335228569581373
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/auth_events.rs // Contains: 4 structs, 3 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/auth_events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_6189035131688022931
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/disputes.rs // Contains: 4 structs, 2 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/disputes.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_1033711192692822915
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/frm.rs // Contains: 4 structs, 3 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/frm.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_6775971572284383959
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/routing_events.rs // Contains: 1 structs, 0 enums #[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>, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/routing_events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_907050958574727750
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/connector_events.rs // Contains: 1 structs, 0 enums #[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>, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/connector_events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3968786266688224990
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/active_payments.rs // Contains: 3 structs, 1 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/active_payments.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_369190685610843770
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/search.rs // Contains: 12 structs, 3 enums 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, 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/search.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 12, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-3140376933244026484
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/sdk_events.rs // Contains: 5 structs, 3 enums 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, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/sdk_events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_router_env_1457848283236610338
clm
file
// Repository: hyperswitch // Crate: router_env // File: crates/router_env/src/logger/config.rs // Contains: 6 structs, 1 enums //! Logger-specific config. use std::path::PathBuf; use serde::Deserialize; /// Config settings. #[derive(Debug, Deserialize, Clone)] pub struct Config { /// Logging to a file. pub log: Log, } /// Log config settings. #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Log { /// Logging to a file. pub file: LogFile, /// Logging to a console. pub console: LogConsole, /// Telemetry / tracing. pub telemetry: LogTelemetry, } /// Logging to a file. #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct LogFile { /// Whether you want to store log in log files. pub enabled: bool, /// Where to store log files. pub path: String, /// Name of log file without suffix. pub file_name: String, /// What gets into log files. pub level: Level, /// Directive which sets the log level for one or more crates/modules. pub filtering_directive: Option<String>, // pub do_async: bool, // is not used // pub rotation: u16, } /// Describes the level of verbosity of a span or event. #[derive(Debug, Clone, Copy)] pub struct Level(pub(super) tracing::Level); impl Level { /// Returns the most verbose [`tracing::Level`] pub fn into_level(self) -> tracing::Level { self.0 } } impl<'de> Deserialize<'de> for Level { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { use std::str::FromStr as _; let s = String::deserialize(deserializer)?; tracing::Level::from_str(&s) .map(Level) .map_err(serde::de::Error::custom) } } /// Logging to a console. #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct LogConsole { /// Whether you want to see log in your terminal. pub enabled: bool, /// What you see in your terminal. pub level: Level, /// Log format #[serde(default)] pub log_format: LogFormat, /// Directive which sets the log level for one or more crates/modules. pub filtering_directive: Option<String>, } /// Telemetry / tracing. #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LogTelemetry { /// Whether the traces pipeline is enabled. pub traces_enabled: bool, /// Whether the metrics pipeline is enabled. pub metrics_enabled: bool, /// Whether errors in setting up traces or metrics pipelines must be ignored. pub ignore_errors: bool, /// Sampling rate for traces pub sampling_rate: Option<f64>, /// Base endpoint URL to send metrics and traces to. Can optionally include the port number. pub otel_exporter_otlp_endpoint: Option<String>, /// Timeout (in milliseconds) for sending metrics and traces. pub otel_exporter_otlp_timeout: Option<u64>, /// Whether to use xray ID generator, (enable this if you plan to use AWS-XRAY) pub use_xray_generator: bool, /// Route Based Tracing pub route_to_trace: Option<Vec<String>>, /// Interval for collecting the metrics (such as gauge) in background thread pub bg_metrics_collection_interval_in_secs: Option<u16>, } /// Telemetry / tracing. #[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum LogFormat { /// Default pretty log format Default, /// JSON based structured logging #[default] Json, /// JSON based structured logging with pretty print PrettyJson, } impl Config { /// Default constructor. pub fn new() -> Result<Self, config::ConfigError> { Self::new_with_config_path(None) } /// Constructor expecting config path set explicitly. pub fn new_with_config_path( explicit_config_path: Option<PathBuf>, ) -> Result<Self, config::ConfigError> { // Configuration values are picked up in the following priority order (1 being least // priority): // 1. Defaults from the implementation of the `Default` trait. // 2. Values from config file. The config file accessed depends on the environment // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of // `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`, // `/config/development.toml` file is read. // 3. Environment variables prefixed with `ROUTER` and each level separated by double // underscores. // // Values in config file override the defaults in `Default` trait, and the values set using // environment variables override both the defaults and the config file values. let environment = crate::env::which(); let config_path = Self::config_path(&environment.to_string(), explicit_config_path); let config = Self::builder(&environment.to_string())? .add_source(config::File::from(config_path).required(false)) .add_source(config::Environment::with_prefix("ROUTER").separator("__")) .build()?; // The logger may not yet be initialized when constructing the application configuration #[allow(clippy::print_stderr)] serde_path_to_error::deserialize(config).map_err(|error| { crate::error!(%error, "Unable to deserialize configuration"); eprintln!("Unable to deserialize application configuration: {error}"); error.into_inner() }) } /// Construct config builder extending it by fall-back defaults and setting config file to load. pub fn builder( environment: &str, ) -> Result<config::ConfigBuilder<config::builder::DefaultState>, config::ConfigError> { config::Config::builder() // Here, it should be `set_override()` not `set_default()`. // "env" can't be altered by config field. // Should be single source of truth. .set_override("env", environment) } /// Config path. pub fn config_path(environment: &str, explicit_config_path: Option<PathBuf>) -> PathBuf { let mut config_path = PathBuf::new(); if let Some(explicit_config_path_val) = explicit_config_path { config_path.push(explicit_config_path_val); } else { let config_file_name = match environment { "production" => "production.toml", "sandbox" => "sandbox.toml", _ => "development.toml", }; let config_directory = Self::get_config_directory(); config_path.push(config_directory); config_path.push(config_file_name); } config_path } /// Get the Directory for the config file /// Read the env variable `CONFIG_DIR` or fallback to `config` pub fn get_config_directory() -> PathBuf { let mut config_path = PathBuf::new(); let config_directory = std::env::var(crate::env::vars::CONFIG_DIR).unwrap_or_else(|_| "config".into()); config_path.push(crate::env::workspace_path()); config_path.push(config_directory); config_path } }
{ "crate": "router_env", "file": "crates/router_env/src/logger/config.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_router_env_1921947234727909023
clm
file
// Repository: hyperswitch // Crate: router_env // File: crates/router_env/src/logger/formatter.rs // Contains: 1 structs, 1 enums //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. use std::{ collections::{HashMap, HashSet}, fmt, io::Write, sync::LazyLock, }; use config::ConfigError; use serde::ser::{SerializeMap, Serializer}; use serde_json::{ser::Formatter, Value}; // use time::format_description::well_known::Rfc3339; use time::format_description::well_known::Iso8601; use tracing::{Event, Metadata, Subscriber}; use tracing_subscriber::{ fmt::MakeWriter, layer::Context, registry::{LookupSpan, SpanRef}, Layer, }; use crate::Storage; // TODO: Documentation coverage for this crate // Implicit keys const MESSAGE: &str = "message"; const HOSTNAME: &str = "hostname"; const PID: &str = "pid"; const ENV: &str = "env"; const VERSION: &str = "version"; const BUILD: &str = "build"; const LEVEL: &str = "level"; const TARGET: &str = "target"; const SERVICE: &str = "service"; const LINE: &str = "line"; const FILE: &str = "file"; const FN: &str = "fn"; const FULL_NAME: &str = "full_name"; const TIME: &str = "time"; // Extra implicit keys. Keys that are provided during runtime but should be treated as // implicit in the logs const FLOW: &str = "flow"; const MERCHANT_AUTH: &str = "merchant_authentication"; const MERCHANT_ID: &str = "merchant_id"; const REQUEST_METHOD: &str = "request_method"; const REQUEST_URL_PATH: &str = "request_url_path"; const REQUEST_ID: &str = "request_id"; const WORKFLOW_ID: &str = "workflow_id"; const GLOBAL_ID: &str = "global_id"; const SESSION_ID: &str = "session_id"; /// Set of predefined implicit keys. pub static IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| { let mut set = rustc_hash::FxHashSet::default(); set.insert(HOSTNAME); set.insert(PID); set.insert(ENV); set.insert(VERSION); set.insert(BUILD); set.insert(LEVEL); set.insert(TARGET); set.insert(SERVICE); set.insert(LINE); set.insert(FILE); set.insert(FN); set.insert(FULL_NAME); set.insert(TIME); set }); /// Extra implicit keys. Keys that are not purely implicit but need to be logged alongside /// other implicit keys in the log json. pub static EXTRA_IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| { let mut set = rustc_hash::FxHashSet::default(); set.insert(MESSAGE); set.insert(FLOW); set.insert(MERCHANT_AUTH); set.insert(MERCHANT_ID); set.insert(REQUEST_METHOD); set.insert(REQUEST_URL_PATH); set.insert(REQUEST_ID); set.insert(GLOBAL_ID); set.insert(SESSION_ID); set.insert(WORKFLOW_ID); set }); /// Describe type of record: entering a span, exiting a span, an event. #[derive(Clone, Debug)] pub enum RecordType { /// Entering a span. EnterSpan, /// Exiting a span. ExitSpan, /// Event. Event, } impl fmt::Display for RecordType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let repr = match self { Self::EnterSpan => "START", Self::ExitSpan => "END", Self::Event => "EVENT", }; write!(f, "{repr}") } } /// Format log records. /// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries. #[derive(Debug)] pub struct FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { dst_writer: W, pid: u32, hostname: String, env: String, service: String, #[cfg(feature = "vergen")] version: String, #[cfg(feature = "vergen")] build: String, default_fields: HashMap<String, Value>, formatter: F, } impl<W, F> FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { /// Constructor of `FormattingLayer`. /// /// A `name` will be attached to all records during formatting. /// A `dst_writer` to forward all records. /// /// ## Example /// ```rust /// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter); /// ``` pub fn new( service: &str, dst_writer: W, formatter: F, ) -> error_stack::Result<Self, ConfigError> { Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter) } /// Construct of `FormattingLayer with implicit default entries. pub fn new_with_implicit_entries( service: &str, dst_writer: W, default_fields: HashMap<String, Value>, formatter: F, ) -> error_stack::Result<Self, ConfigError> { let pid = std::process::id(); let hostname = gethostname::gethostname().to_string_lossy().into_owned(); let service = service.to_string(); #[cfg(feature = "vergen")] let version = crate::version!().to_string(); #[cfg(feature = "vergen")] let build = crate::build!().to_string(); let env = crate::env::which().to_string(); for key in default_fields.keys() { if IMPLICIT_KEYS.contains(key.as_str()) { return Err(ConfigError::Message(format!( "A reserved key `{key}` was included in `default_fields` in the log formatting layer" )) .into()); } } Ok(Self { dst_writer, pid, hostname, env, service, #[cfg(feature = "vergen")] version, #[cfg(feature = "vergen")] build, default_fields, formatter, }) } /// Serialize common for both span and event entries. fn common_serialize<S>( &self, map_serializer: &mut impl SerializeMap<Error = serde_json::Error>, metadata: &Metadata<'_>, span: Option<&SpanRef<'_, S>>, storage: &Storage<'_>, name: &str, ) -> Result<(), std::io::Error> where S: Subscriber + for<'a> LookupSpan<'a>, { let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s); let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s); map_serializer.serialize_entry(HOSTNAME, &self.hostname)?; map_serializer.serialize_entry(PID, &self.pid)?; map_serializer.serialize_entry(ENV, &self.env)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(VERSION, &self.version)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(BUILD, &self.build)?; map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?; map_serializer.serialize_entry(TARGET, metadata.target())?; map_serializer.serialize_entry(SERVICE, &self.service)?; map_serializer.serialize_entry(LINE, &metadata.line())?; map_serializer.serialize_entry(FILE, &metadata.file())?; map_serializer.serialize_entry(FN, name)?; map_serializer .serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?; if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) { map_serializer.serialize_entry(TIME, time)?; } // Write down implicit default entries. for (key, value) in self.default_fields.iter() { map_serializer.serialize_entry(key, value)?; } #[cfg(feature = "log_custom_entries_to_extra")] let mut extra = serde_json::Map::default(); let mut explicit_entries_set: HashSet<&str> = HashSet::default(); // Write down explicit event's entries. for (key, value) in storage.values.iter() { if is_extra_implicit(key) { #[cfg(feature = "log_extra_implicit_fields")] map_serializer.serialize_entry(key, value)?; explicit_entries_set.insert(key); } else if is_extra(key) { #[cfg(feature = "log_custom_entries_to_extra")] extra.insert(key.to_string(), value.clone()); #[cfg(not(feature = "log_custom_entries_to_extra"))] map_serializer.serialize_entry(key, value)?; explicit_entries_set.insert(key); } else { tracing::warn!( ?key, ?value, "Attempting to log a reserved entry. It won't be added to the logs" ); } } // Write down entries from the span, if it exists. if let Some(span) = &span { let extensions = span.extensions(); if let Some(visitor) = extensions.get::<Storage<'_>>() { for (key, value) in &visitor.values { if is_extra_implicit(key) && !explicit_entries_set.contains(key) { #[cfg(feature = "log_extra_implicit_fields")] map_serializer.serialize_entry(key, value)?; } else if is_extra(key) && !explicit_entries_set.contains(key) { #[cfg(feature = "log_custom_entries_to_extra")] extra.insert(key.to_string(), value.clone()); #[cfg(not(feature = "log_custom_entries_to_extra"))] map_serializer.serialize_entry(key, value)?; } else { tracing::warn!( ?key, ?value, "Attempting to log a reserved entry. It won't be added to the logs" ); } } } } #[cfg(feature = "log_custom_entries_to_extra")] map_serializer.serialize_entry("extra", &extra)?; Ok(()) } /// Flush memory buffer into an output stream trailing it with next line. /// /// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading. fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> { buffer.write_all(b"\n")?; self.dst_writer.make_writer().write_all(&buffer) } /// Serialize entries of span. fn span_serialize<S>( &self, span: &SpanRef<'_, S>, ty: RecordType, ) -> Result<Vec<u8>, std::io::Error> where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let message = Self::span_message(span, ty); let mut storage = Storage::default(); storage.record_value("message", message.into()); self.common_serialize( &mut map_serializer, span.metadata(), Some(span), &storage, span.name(), )?; map_serializer.end()?; Ok(buffer) } /// Serialize event into a buffer of bytes using parent span. pub fn event_serialize<S>( &self, span: Option<&SpanRef<'_, S>>, event: &Event<'_>, ) -> std::io::Result<Vec<u8>> where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let mut storage = Storage::default(); event.record(&mut storage); let name = span.map_or("?", SpanRef::name); Self::event_message(span, event, &mut storage); self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?; map_serializer.end()?; Ok(buffer) } /// Format message of a span. /// /// Example: "[FN_WITHOUT_COLON - START]" fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String where S: Subscriber + for<'a> LookupSpan<'a>, { format!("[{} - {}]", span.metadata().name().to_uppercase(), ty) } /// Format message of an event. /// /// Examples: "[FN_WITHOUT_COLON - EVENT] Message" fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>) where S: Subscriber + for<'a> LookupSpan<'a>, { // Get value of kept "message" or "target" if does not exist. let message = storage .values .entry("message") .or_insert_with(|| event.metadata().target().into()); // Prepend the span name to the message if span exists. if let (Some(span), Value::String(a)) = (span, message) { *a = format!("{} {}", Self::span_message(span, RecordType::Event), a,); } } } #[allow(clippy::expect_used)] impl<S, W, F> Layer<S> for FormattingLayer<W, F> where S: Subscriber + for<'a> LookupSpan<'a>, W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone + 'static, { fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) { // Event could have no span. let span = ctx.lookup_current(); let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event); if let Ok(formatted) = result { let _ = self.flush(formatted); } } #[cfg(feature = "log_active_span_json")] fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(id).expect("No span"); if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) { let _ = self.flush(serialized); } } #[cfg(not(feature = "log_active_span_json"))] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); if span.parent().is_none() { if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { let _ = self.flush(serialized); } } } #[cfg(feature = "log_active_span_json")] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { let _ = self.flush(serialized); } } }
{ "crate": "router_env", "file": "crates/router_env/src/logger/formatter.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_env_8842475033338704846
clm
file
// Repository: hyperswitch // Crate: router_env // File: crates/router_env/src/logger/storage.rs // Contains: 2 structs, 0 enums //! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. use std::{collections::HashMap, fmt, time::Instant}; use tracing::{ field::{Field, Visit}, span::{Attributes, Record}, Id, Subscriber, }; use tracing_subscriber::{layer::Context, Layer}; /// Storage to store key value pairs of spans. #[derive(Clone, Debug)] pub struct StorageSubscription; /// Storage to store key value pairs of spans. /// When new entry is crated it stores it in [HashMap] which is owned by `extensions`. #[derive(Clone, Debug)] pub struct Storage<'a> { /// Hash map to store values. pub values: HashMap<&'a str, serde_json::Value>, } impl<'a> Storage<'a> { /// Default constructor. pub fn new() -> Self { Self::default() } pub fn record_value(&mut self, key: &'a str, value: serde_json::Value) { if super::formatter::IMPLICIT_KEYS.contains(key) { tracing::warn!(value =? value, "{} is a reserved entry. Skipping it.", key); } else { self.values.insert(key, value); } } } /// Default constructor. impl Default for Storage<'_> { fn default() -> Self { Self { values: HashMap::new(), } } } /// Visitor to store entry. impl Visit for Storage<'_> { /// A i64. fn record_i64(&mut self, field: &Field, value: i64) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A u64. fn record_u64(&mut self, field: &Field, value: u64) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A 64-bit floating point. fn record_f64(&mut self, field: &Field, value: f64) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A boolean. fn record_bool(&mut self, field: &Field, value: bool) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A string. fn record_str(&mut self, field: &Field, value: &str) { self.record_value(field.name(), serde_json::Value::from(value)); } /// Otherwise. fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { match field.name() { // Skip fields which are already handled name if name.starts_with("log.") => (), name if name.starts_with("r#") => { self.record_value( #[allow(clippy::expect_used)] name.get(2..) .expect("field name must have a minimum of two characters"), serde_json::Value::from(format!("{value:?}")), ); } name => { self.record_value(name, serde_json::Value::from(format!("{value:?}"))); } }; } } const PERSISTENT_KEYS: [&str; 6] = [ "payment_id", "connector_name", "merchant_id", "flow", "payment_method", "status_code", ]; impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S> for StorageSubscription { /// On new span. fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(id).expect("No span"); let mut extensions = span.extensions_mut(); let mut visitor = if let Some(parent_span) = span.parent() { let mut extensions = parent_span.extensions_mut(); extensions .get_mut::<Storage<'_>>() .map(|v| v.to_owned()) .unwrap_or_default() } else { Storage::default() }; attrs.record(&mut visitor); extensions.insert(visitor); } /// On additional key value pairs store it. fn on_record(&self, span: &Id, values: &Record<'_>, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(span).expect("No span"); let mut extensions = span.extensions_mut(); #[allow(clippy::expect_used)] let visitor = extensions .get_mut::<Storage<'_>>() .expect("The span does not have storage"); values.record(visitor); } /// On enter store time. fn on_enter(&self, span: &Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(span).expect("No span"); let mut extensions = span.extensions_mut(); if extensions.get_mut::<Instant>().is_none() { extensions.insert(Instant::now()); } } /// On close create an entry about how long did it take. fn on_close(&self, span: Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(&span).expect("No span"); let elapsed_milliseconds = { let extensions = span.extensions(); extensions .get::<Instant>() .map(|i| i.elapsed().as_millis()) .unwrap_or(0) }; if let Some(s) = span.extensions().get::<Storage<'_>>() { s.values.iter().for_each(|(k, v)| { if PERSISTENT_KEYS.contains(k) { span.parent().and_then(|p| { p.extensions_mut() .get_mut::<Storage<'_>>() .map(|s| s.record_value(k, v.to_owned())) }); } }) }; let mut extensions_mut = span.extensions_mut(); #[allow(clippy::expect_used)] let visitor = extensions_mut .get_mut::<Storage<'_>>() .expect("No visitor in extensions"); if let Ok(elapsed) = serde_json::to_value(elapsed_milliseconds) { visitor.record_value("elapsed_milliseconds", elapsed); } } }
{ "crate": "router_env", "file": "crates/router_env/src/logger/storage.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_env_-5399519940548685046
clm
file
// Repository: hyperswitch // Crate: router_env // File: crates/router_env/src/logger/setup.rs // Contains: 3 structs, 1 enums //! Setup logging subsystem. use std::time::Duration; use ::config::ConfigError; use serde_json::ser::{CompactFormatter, PrettyFormatter}; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer}; use crate::{config, FormattingLayer, StorageSubscription}; /// Contains guards necessary for logging and metrics collection. #[derive(Debug)] pub struct TelemetryGuard { _log_guards: Vec<WorkerGuard>, } /// Setup logging sub-system specifying the logging configuration, service (binary) name, and a /// list of external crates for which a more verbose logging must be enabled. All crates within the /// current cargo workspace are automatically considered for verbose logging. #[allow(clippy::print_stdout)] // The logger hasn't been initialized yet pub fn setup( config: &config::Log, service_name: &str, crates_to_filter: impl AsRef<[&'static str]>, ) -> error_stack::Result<TelemetryGuard, ConfigError> { let mut guards = Vec::new(); // Setup OpenTelemetry traces and metrics let traces_layer = if config.telemetry.traces_enabled { setup_tracing_pipeline(&config.telemetry, service_name) } else { None }; if config.telemetry.metrics_enabled { setup_metrics_pipeline(&config.telemetry) }; // Setup file logging let file_writer = if config.file.enabled { let mut path = crate::env::workspace_path(); // Using an absolute path for file log path would replace workspace path with absolute path, // which is the intended behavior for us. path.push(&config.file.path); let file_appender = tracing_appender::rolling::hourly(&path, &config.file.file_name); let (file_writer, guard) = tracing_appender::non_blocking(file_appender); guards.push(guard); let file_filter = get_envfilter( config.file.filtering_directive.as_ref(), config::Level(tracing::Level::WARN), config.file.level, &crates_to_filter, ); println!("Using file logging filter: {file_filter}"); let layer = FormattingLayer::new(service_name, file_writer, CompactFormatter)? .with_filter(file_filter); Some(layer) } else { None }; let subscriber = tracing_subscriber::registry() .with(traces_layer) .with(StorageSubscription) .with(file_writer); // Setup console logging if config.console.enabled { let (console_writer, guard) = tracing_appender::non_blocking(std::io::stdout()); guards.push(guard); let console_filter = get_envfilter( config.console.filtering_directive.as_ref(), config::Level(tracing::Level::WARN), config.console.level, &crates_to_filter, ); println!("Using console logging filter: {console_filter}"); match config.console.log_format { config::LogFormat::Default => { let logging_layer = fmt::layer() .with_timer(fmt::time::time()) .pretty() .with_writer(console_writer) .with_filter(console_filter); subscriber.with(logging_layer).init(); } config::LogFormat::Json => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); subscriber .with( FormattingLayer::new(service_name, console_writer, CompactFormatter)? .with_filter(console_filter), ) .init(); } config::LogFormat::PrettyJson => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); subscriber .with( FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())? .with_filter(console_filter), ) .init(); } } } else { subscriber.init(); }; // Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is // dropped Ok(TelemetryGuard { _log_guards: guards, }) } fn get_opentelemetry_exporter_config( config: &config::LogTelemetry, ) -> opentelemetry_otlp::ExportConfig { let mut exporter_config = opentelemetry_otlp::ExportConfig { protocol: opentelemetry_otlp::Protocol::Grpc, endpoint: config.otel_exporter_otlp_endpoint.clone(), ..Default::default() }; if let Some(timeout) = config.otel_exporter_otlp_timeout { exporter_config.timeout = Duration::from_millis(timeout); } exporter_config } #[derive(Debug, Clone)] enum TraceUrlAssert { Match(String), EndsWith(String), } impl TraceUrlAssert { fn compare_url(&self, url: &str) -> bool { match self { Self::Match(value) => url == value, Self::EndsWith(end) => url.ends_with(end), } } } impl From<String> for TraceUrlAssert { fn from(value: String) -> Self { match value { url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()), url => Self::Match(url), } } } #[derive(Debug, Clone)] struct TraceAssertion { clauses: Option<Vec<TraceUrlAssert>>, /// default behaviour for tracing if no condition is provided default: bool, } impl TraceAssertion { /// Should the provided url be traced fn should_trace_url(&self, url: &str) -> bool { match &self.clauses { Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)), None => self.default, } } } /// Conditional Sampler for providing control on url based tracing #[derive(Clone, Debug)] struct ConditionalSampler<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>( TraceAssertion, T, ); impl<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static> opentelemetry_sdk::trace::ShouldSample for ConditionalSampler<T> { fn should_sample( &self, parent_context: Option<&opentelemetry::Context>, trace_id: opentelemetry::trace::TraceId, name: &str, span_kind: &opentelemetry::trace::SpanKind, attributes: &[opentelemetry::KeyValue], links: &[opentelemetry::trace::Link], ) -> opentelemetry::trace::SamplingResult { use opentelemetry::trace::TraceContextExt; match attributes .iter() .find(|&kv| kv.key == opentelemetry::Key::new("http.route")) .map_or(self.0.default, |inner| { self.0.should_trace_url(&inner.value.as_str()) }) { true => { self.1 .should_sample(parent_context, trace_id, name, span_kind, attributes, links) } false => opentelemetry::trace::SamplingResult { decision: opentelemetry::trace::SamplingDecision::Drop, attributes: Vec::new(), trace_state: match parent_context { Some(ctx) => ctx.span().span_context().trace_state().clone(), None => opentelemetry::trace::TraceState::default(), }, }, } } } fn setup_tracing_pipeline( config: &config::LogTelemetry, service_name: &str, ) -> Option< tracing_opentelemetry::OpenTelemetryLayer< tracing_subscriber::Registry, opentelemetry_sdk::trace::Tracer, >, > { use opentelemetry::trace::TracerProvider; use opentelemetry_otlp::WithExportConfig; use opentelemetry_sdk::trace; opentelemetry::global::set_text_map_propagator( opentelemetry_sdk::propagation::TraceContextPropagator::new(), ); // Set the export interval to 1 second let batch_config = trace::BatchConfigBuilder::default() .with_scheduled_delay(Duration::from_millis(1000)) .build(); let exporter_result = opentelemetry_otlp::SpanExporter::builder() .with_tonic() .with_export_config(get_opentelemetry_exporter_config(config)) .build(); let exporter = if config.ignore_errors { #[allow(clippy::print_stderr)] // The logger hasn't been initialized yet exporter_result .inspect_err(|error| eprintln!("Failed to build traces exporter: {error:?}")) .ok()? } else { // Safety: This is conditional, there is an option to avoid this behavior at runtime. #[allow(clippy::expect_used)] exporter_result.expect("Failed to build traces exporter") }; let mut provider_builder = trace::TracerProvider::builder() .with_span_processor( trace::BatchSpanProcessor::builder( exporter, // The runtime would have to be updated if a different web framework is used opentelemetry_sdk::runtime::TokioCurrentThread, ) .with_batch_config(batch_config) .build(), ) .with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler( TraceAssertion { clauses: config .route_to_trace .clone() .map(|inner| inner.into_iter().map(TraceUrlAssert::from).collect()), default: false, }, trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)), )))) .with_resource(opentelemetry_sdk::Resource::new(vec![ opentelemetry::KeyValue::new("service.name", service_name.to_owned()), ])); if config.use_xray_generator { provider_builder = provider_builder .with_id_generator(opentelemetry_aws::trace::XrayIdGenerator::default()); } Some( tracing_opentelemetry::layer() .with_tracer(provider_builder.build().tracer(service_name.to_owned())), ) } fn setup_metrics_pipeline(config: &config::LogTelemetry) { use opentelemetry_otlp::WithExportConfig; let exporter_result = opentelemetry_otlp::MetricExporter::builder() .with_tonic() .with_temporality(opentelemetry_sdk::metrics::Temporality::Cumulative) .with_export_config(get_opentelemetry_exporter_config(config)) .build(); let exporter = if config.ignore_errors { #[allow(clippy::print_stderr)] // The logger hasn't been initialized yet exporter_result .inspect_err(|error| eprintln!("Failed to build metrics exporter: {error:?}")) .ok(); return; } else { // Safety: This is conditional, there is an option to avoid this behavior at runtime. #[allow(clippy::expect_used)] exporter_result.expect("Failed to build metrics exporter") }; let reader = opentelemetry_sdk::metrics::PeriodicReader::builder( exporter, // The runtime would have to be updated if a different web framework is used opentelemetry_sdk::runtime::TokioCurrentThread, ) .with_interval(Duration::from_secs(3)) .with_timeout(Duration::from_secs(10)) .build(); let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder() .with_reader(reader) .with_resource(opentelemetry_sdk::Resource::new([ opentelemetry::KeyValue::new( "pod", std::env::var("POD_NAME").unwrap_or(String::from("hyperswitch-server-default")), ), ])) .build(); opentelemetry::global::set_meter_provider(provider); } fn get_envfilter( filtering_directive: Option<&String>, default_log_level: config::Level, filter_log_level: config::Level, crates_to_filter: impl AsRef<[&'static str]>, ) -> EnvFilter { filtering_directive .map(|filter| { // Try to create target filter from specified filtering directive, if set // Safety: If user is overriding the default filtering directive, then we need to panic // for invalid directives. #[allow(clippy::expect_used)] EnvFilter::builder() .with_default_directive(default_log_level.into_level().into()) .parse(filter) .expect("Invalid EnvFilter filtering directive") }) .unwrap_or_else(|| { // Construct a default target filter otherwise let mut workspace_members = crate::cargo_workspace_members!(); workspace_members.extend(crates_to_filter.as_ref()); workspace_members .drain() .zip(std::iter::repeat(filter_log_level.into_level())) .fold( EnvFilter::default().add_directive(default_log_level.into_level().into()), |env_filter, (target, level)| { // Safety: This is a hardcoded basic filtering directive. If even the basic // filter is wrong, it's better to panic. #[allow(clippy::expect_used)] env_filter.add_directive( format!("{target}={level}") .parse() .expect("Invalid EnvFilter directive format"), ) }, ) }) }
{ "crate": "router_env", "file": "crates/router_env/src/logger/setup.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_redis_interface_6914026961191246021
clm
file
// Repository: hyperswitch // Crate: redis_interface // File: crates/redis_interface/src/types.rs // Contains: 2 structs, 9 enums //! Data types and type conversions //! from `fred`'s internal data-types to custom data-types use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; use crate::{errors, RedisConnectionPool}; pub struct RedisValue { inner: FredRedisValue, } impl std::ops::Deref for RedisValue { type Target = FredRedisValue; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisValue { pub fn new(value: FredRedisValue) -> Self { Self { inner: value } } pub fn into_inner(self) -> FredRedisValue { self.inner } pub fn from_bytes(val: Vec<u8>) -> Self { Self { inner: FredRedisValue::Bytes(val.into()), } } pub fn from_string(value: String) -> Self { Self { inner: FredRedisValue::String(value.into()), } } } impl From<RedisValue> for FredRedisValue { fn from(v: RedisValue) -> Self { v.inner } } #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct RedisSettings { pub host: String, pub port: u16, pub cluster_enabled: bool, pub cluster_urls: Vec<String>, pub use_legacy_version: bool, pub pool_size: usize, pub reconnect_max_attempts: u32, /// Reconnect delay in milliseconds pub reconnect_delay: u32, /// TTL in seconds pub default_ttl: u32, /// TTL for hash-tables in seconds pub default_hash_ttl: u32, pub stream_read_count: u64, pub auto_pipeline: bool, pub disable_auto_backpressure: bool, pub max_in_flight_commands: u64, pub default_command_timeout: u64, pub max_feed_count: u64, pub unresponsive_timeout: u64, } impl RedisSettings { /// Validates the Redis configuration provided. pub fn validate(&self) -> CustomResult<(), errors::RedisError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; when(self.host.is_default_or_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `host` must be specified".into(), )) })?; when(self.cluster_enabled && self.cluster_urls.is_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), )) })?; when( self.default_command_timeout < self.unresponsive_timeout, || { Err(errors::RedisError::InvalidConfiguration( "Unresponsive timeout cannot be greater than the command timeout".into(), ) .into()) }, ) } } impl Default for RedisSettings { fn default() -> Self { Self { host: "127.0.0.1".to_string(), port: 6379, cluster_enabled: false, cluster_urls: vec![], use_legacy_version: false, pool_size: 5, reconnect_max_attempts: 5, reconnect_delay: 5, default_ttl: 300, stream_read_count: 1, default_hash_ttl: 900, auto_pipeline: true, disable_auto_backpressure: false, max_in_flight_commands: 5000, default_command_timeout: 30, max_feed_count: 200, unresponsive_timeout: 10, } } } #[derive(Debug)] pub enum RedisEntryId { UserSpecifiedID { milliseconds: String, sequence_number: String, }, AutoGeneratedID, AfterLastID, /// Applicable only with consumer groups UndeliveredEntryID, } impl From<RedisEntryId> for fred::types::XID { fn from(id: RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } impl From<&RedisEntryId> for fred::types::XID { fn from(id: &RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } #[derive(Eq, PartialEq)] pub enum SetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for SetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { // Returns String ( "OK" ) in case of success fred::types::RedisValue::String(_) => Ok(Self::KeySet), // Return Null in case of failure fred::types::RedisValue::Null => Ok(Self::KeyNotSet), // Unexpected behaviour _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected SETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum HsetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for HsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected HSETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum MsetnxReply { KeysSet, KeysNotSet, // At least one existing key } impl fred::types::FromRedis for MsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet), fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected MSETNX command reply", )), } } } #[derive(Debug)] pub enum StreamCapKind { MinID, MaxLen, } impl From<StreamCapKind> for fred::types::XCapKind { fn from(item: StreamCapKind) -> Self { match item { StreamCapKind::MaxLen => Self::MaxLen, StreamCapKind::MinID => Self::MinID, } } } #[derive(Debug)] pub enum StreamCapTrim { Exact, AlmostExact, } impl From<StreamCapTrim> for fred::types::XCapTrim { fn from(item: StreamCapTrim) -> Self { match item { StreamCapTrim::Exact => Self::Exact, StreamCapTrim::AlmostExact => Self::AlmostExact, } } } #[derive(Debug)] pub enum DelReply { KeyDeleted, KeyNotDeleted, // Key not found } impl DelReply { pub fn is_key_deleted(&self) -> bool { matches!(self, Self::KeyDeleted) } pub fn is_key_not_deleted(&self) -> bool { matches!(self, Self::KeyNotDeleted) } } impl fred::types::FromRedis for DelReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected del command reply", )), } } } #[derive(Debug)] pub enum SaddReply { KeySet, KeyNotSet, } impl fred::types::FromRedis for SaddReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected sadd command reply", )), } } } #[derive(Debug)] pub enum SetGetReply<T> { ValueSet(T), // Value was set and this is the value that was set ValueExists(T), // Value already existed and this is the existing value } impl<T> SetGetReply<T> { pub fn get_value(&self) -> &T { match self { Self::ValueSet(value) => value, Self::ValueExists(value) => value, } } } #[derive(Debug)] pub struct RedisKey(String); impl RedisKey { pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String { pool.add_prefix(&self.0) } pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String { self.0.clone() } } impl<T: AsRef<str>> From<T> for RedisKey { fn from(value: T) -> Self { let value = value.as_ref(); Self(value.to_string()) } }
{ "crate": "redis_interface", "file": "crates/redis_interface/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 9, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_redis_interface_6102390552522096334
clm
file
// Repository: hyperswitch // Crate: redis_interface // File: crates/redis_interface/src/commands.rs // Contains: 1 structs, 0 enums //! An interface to abstract the `fred` commands //! //! The folder provides generic functions for providing serialization //! and deserialization while calling redis. //! It also includes instruments to provide tracing. use std::fmt::Debug; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, ByteSliceExt, Encode, StringExt}, fp_utils, }; use error_stack::{report, ResultExt}; use fred::{ interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface}, prelude::{LuaInterface, RedisErrorKind}, types::{ Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings, MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse, }, }; use futures::StreamExt; use tracing::instrument; use crate::{ errors, types::{ DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply, SetnxReply, }, }; impl super::RedisConnectionPool { pub fn add_prefix(&self, key: &str) -> String { if self.key_prefix.is_empty() { key.to_string() } else { format!("{}:{}", self.key_prefix, key) } } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX(self.config.default_ttl.into())), None, false, ) .await .change_context(errors::RedisError::SetFailed) } pub async fn set_key_without_modifying_ttl<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::KEEPTTL), None, false, ) .await .change_context(errors::RedisError::SetFailed) } pub async fn set_multiple_keys_if_not_exist<V>( &self, value: V, ) -> CustomResult<MsetnxReply, errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .msetnx(value) .await .change_context(errors::RedisError::SetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_if_not_exist<V>( &self, key: &RedisKey, value: V, ttl: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key(key, serialized.as_slice()).await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_without_modifying_ttl<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_without_modifying_ttl(key, serialized.as_slice()) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.pool .set( key.tenant_aware_key(self), serialized.as_slice(), Some(Expiration::EX(seconds)), None, false, ) .await .change_context(errors::RedisError::SetExFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .get(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .get(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetFailed) } } } } #[instrument(level = "DEBUG", skip(self))] async fn get_multiple_keys_with_mget<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } let tenant_aware_keys: Vec<String> = keys.iter().map(|key| key.tenant_aware_key(self)).collect(); self.pool .mget(tenant_aware_keys) .await .change_context(errors::RedisError::GetFailed) } #[instrument(level = "DEBUG", skip(self))] async fn get_multiple_keys_with_parallel_get<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } let tenant_aware_keys: Vec<String> = keys.iter().map(|key| key.tenant_aware_key(self)).collect(); let futures = tenant_aware_keys .iter() .map(|redis_key| self.pool.get::<Option<V>, _>(redis_key)); let results = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::GetFailed) .attach_printable("Failed to get keys in cluster mode")?; Ok(results) } /// Helper method to encapsulate the logic for choosing between cluster and non-cluster modes #[instrument(level = "DEBUG", skip(self))] async fn get_keys_by_mode<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if self.config.cluster_enabled { // Use individual GET commands for cluster mode to avoid CROSSSLOT errors self.get_multiple_keys_with_parallel_get(keys).await } else { // Use MGET for non-cluster mode for better performance self.get_multiple_keys_with_mget(keys).await } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_multiple_keys<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } match self.get_keys_by_mode(keys).await { Ok(values) => Ok(values), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { let tenant_unaware_keys: Vec<RedisKey> = keys .iter() .map(|key| key.tenant_unaware_key(self).into()) .collect(); self.get_keys_by_mode(&tenant_unaware_keys).await } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError> where V: Into<MultipleKeys> + Unpin + Send + 'static, { match self .pool .exists(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .exists(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetFailed) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_key<T>( &self, key: &RedisKey, type_name: &'static str, ) -> CustomResult<T, errors::RedisError> where T: serde::de::DeserializeOwned, { let value_bytes = self.get_key::<Vec<u8>>(key).await?; fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?; value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_multiple_keys<T>( &self, keys: &[RedisKey], type_name: &'static str, ) -> CustomResult<Vec<Option<T>>, errors::RedisError> where T: serde::de::DeserializeOwned, { let value_bytes_vec = self.get_multiple_keys::<Vec<u8>>(keys).await?; let mut results = Vec::with_capacity(value_bytes_vec.len()); for value_bytes_opt in value_bytes_vec { match value_bytes_opt { Some(value_bytes) => { if value_bytes.is_empty() { results.push(None); } else { let parsed = value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed)?; results.push(Some(parsed)); } } None => results.push(None), } } Ok(results) } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> { match self .pool .del(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .del(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_multiple_keys( &self, keys: &[RedisKey], ) -> CustomResult<Vec<DelReply>, errors::RedisError> { let futures = keys.iter().map(|key| self.delete_key(key)); let del_result = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::DeleteFailed)?; Ok(del_result) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX(seconds)), None, false, ) .await .change_context(errors::RedisError::SetExFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_if_not_exists_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX( seconds.unwrap_or(self.config.default_ttl.into()), )), Some(SetOptions::NX), false, ) .await .change_context(errors::RedisError::SetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_expiry( &self, key: &RedisKey, seconds: i64, ) -> CustomResult<(), errors::RedisError> { self.pool .expire(key.tenant_aware_key(self), seconds) .await .change_context(errors::RedisError::SetExpiryFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_expire_at( &self, key: &RedisKey, timestamp: i64, ) -> CustomResult<(), errors::RedisError> { self.pool .expire_at(key.tenant_aware_key(self), timestamp) .await .change_context(errors::RedisError::SetExpiryFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> { self.pool .ttl(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_fields<V>( &self, key: &RedisKey, values: V, ttl: Option<i64>, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { let output: Result<(), _> = self .pool .hset(key.tenant_aware_key(self), values) .await .change_context(errors::RedisError::SetHashFailed); // setting expiry for the key output .async_and_then(|_| { self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into())) }) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_field_if_not_exist<V>( &self, key: &RedisKey, field: &str, value: V, ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { let output: Result<HsetnxReply, _> = self .pool .hsetnx(key.tenant_aware_key(self), field, value) .await .change_context(errors::RedisError::SetHashFieldFailed); output .async_and_then(|inner| async { self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into()) .await?; Ok(inner) }) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_hash_field_if_not_exist<V>( &self, key: &RedisKey, field: &str, value: V, ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>( &self, kv: &[(&RedisKey, V)], field: &str, ttl: Option<u32>, ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError> where V: serde::Serialize + Debug, { let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len()); for (key, val) in kv { hsetnx.push( self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl) .await?, ); } Ok(hsetnx) } #[instrument(level = "DEBUG", skip(self))] pub async fn increment_fields_in_hash<T>( &self, key: &RedisKey, fields_to_increment: &[(T, i64)], ) -> CustomResult<Vec<usize>, errors::RedisError> where T: Debug + ToString, { let mut values_after_increment = Vec::with_capacity(fields_to_increment.len()); for (field, increment) in fields_to_increment.iter() { values_after_increment.push( self.pool .hincrby(key.tenant_aware_key(self), field.to_string(), *increment) .await .change_context(errors::RedisError::IncrementHashFieldFailed)?, ) } Ok(values_after_increment) } #[instrument(level = "DEBUG", skip(self))] pub async fn hscan( &self, key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() .hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count) .filter_map(|value| async move { match value { Ok(mut v) => { let v = v.take_results()?; let v: Vec<String> = v.iter().filter_map(|(_, val)| val.as_string()).collect(); Some(futures::stream::iter(v)) } Err(err) => { tracing::error!(redis_err=?err, "Redis error while executing hscan command"); None } } }) .flatten() .collect::<Vec<_>>() .await) } #[instrument(level = "DEBUG", skip(self))] pub async fn scan( &self, pattern: &RedisKey, count: Option<u32>, scan_type: Option<ScanType>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() .scan(pattern.tenant_aware_key(self), count, scan_type) .filter_map(|value| async move { match value { Ok(mut v) => { let v = v.take_results()?; let v: Vec<String> = v.into_iter().filter_map(|val| val.into_string()).collect(); Some(futures::stream::iter(v)) } Err(err) => { tracing::error!(redis_err=?err, "Redis error while executing scan command"); None } } }) .flatten() .collect::<Vec<_>>() .await) } #[instrument(level = "DEBUG", skip(self))] pub async fn hscan_and_deserialize<T>( &self, key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<T>, errors::RedisError> where T: serde::de::DeserializeOwned, { let redis_results = self.hscan(key, pattern, count).await?; Ok(redis_results .iter() .filter_map(|v| { let r: T = v.parse_struct(std::any::type_name::<T>()).ok()?; Some(r) }) .collect()) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field<V>( &self, key: &RedisKey, field: &str, ) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .hget(key.tenant_aware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(feature = "multitenancy_fallback")] { self.pool .hget(key.tenant_unaware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) } #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .hgetall(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(feature = "multitenancy_fallback")] { self.pool .hgetall(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) } #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field_and_deserialize<V>( &self, key: &RedisKey, field: &str, type_name: &'static str, ) -> CustomResult<V, errors::RedisError> where V: serde::de::DeserializeOwned, { let value_bytes = self.get_hash_field::<Vec<u8>>(key, field).await?; if value_bytes.is_empty() { return Err(errors::RedisError::NotFound.into()); } value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn sadd<V>( &self, key: &RedisKey, members: V, ) -> CustomResult<SaddReply, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send, V::Error: Into<fred::error::RedisError> + Send, { self.pool .sadd(key.tenant_aware_key(self), members) .await .change_context(errors::RedisError::SetAddMembersFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_append_entry<F>( &self, stream: &RedisKey, entry_id: &RedisEntryId, fields: F, ) -> CustomResult<(), errors::RedisError> where F: TryInto<MultipleOrderedPairs> + Debug + Send + Sync, F::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .xadd(stream.tenant_aware_key(self), false, None, entry_id, fields) .await .change_context(errors::RedisError::StreamAppendFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_delete_entries<Ids>( &self, stream: &RedisKey, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleStrings> + Debug + Send + Sync, { self.pool .xdel(stream.tenant_aware_key(self), ids) .await .change_context(errors::RedisError::StreamDeleteFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_trim_entries<C>( &self, stream: &RedisKey, xcap: C, ) -> CustomResult<usize, errors::RedisError> where C: TryInto<XCap> + Debug + Send + Sync, C::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .xtrim(stream.tenant_aware_key(self), xcap) .await .change_context(errors::RedisError::StreamTrimFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_acknowledge_entries<Ids>( &self, stream: &RedisKey, group: &str, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleIDs> + Debug + Send + Sync, { self.pool .xack(stream.tenant_aware_key(self), group, ids) .await .change_context(errors::RedisError::StreamAcknowledgeFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_get_length( &self, stream: &RedisKey, ) -> CustomResult<usize, errors::RedisError> { self.pool .xlen(stream.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetLengthFailed) } pub fn get_keys_with_prefix<K>(&self, keys: K) -> MultipleKeys where K: Into<MultipleKeys> + Debug + Send + Sync, { let multiple_keys: MultipleKeys = keys.into(); let res = multiple_keys .inner() .iter() .filter_map(|key| key.as_str().map(RedisKey::from)) .map(|k: RedisKey| k.tenant_aware_key(self)) .collect::<Vec<_>>(); MultipleKeys::from(res) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_read_entries<K, Ids>( &self, streams: K, ids: Ids, read_count: Option<u64>, ) -> CustomResult<XReadResponse<String, String, String, String>, errors::RedisError> where K: Into<MultipleKeys> + Debug + Send + Sync, Ids: Into<MultipleIDs> + Debug + Send + Sync, { let strms = self.get_keys_with_prefix(streams); self.pool .xread_map( Some(read_count.unwrap_or(self.config.default_stream_read_count)), None, strms, ids, ) .await .map_err(|err| match err.kind() { RedisErrorKind::NotFound | RedisErrorKind::Parse => { report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable) } _ => report!(err).change_context(errors::RedisError::StreamReadFailed), }) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_read_with_options<K, Ids>( &self, streams: K, ids: Ids, count: Option<u64>, block: Option<u64>, // timeout in milliseconds group: Option<(&str, &str)>, // (group_name, consumer_name) ) -> CustomResult<XReadResponse<String, String, String, Option<String>>, errors::RedisError> where K: Into<MultipleKeys> + Debug + Send + Sync, Ids: Into<MultipleIDs> + Debug + Send + Sync, { match group { Some((group_name, consumer_name)) => { self.pool .xreadgroup_map( group_name, consumer_name, count, block, false, self.get_keys_with_prefix(streams), ids, ) .await } None => { self.pool .xread_map(count, block, self.get_keys_with_prefix(streams), ids) .await } } .map_err(|err| match err.kind() { RedisErrorKind::NotFound | RedisErrorKind::Parse => { report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable) } _ => report!(err).change_context(errors::RedisError::StreamReadFailed), }) } #[instrument(level = "DEBUG", skip(self))] pub async fn append_elements_to_list<V>( &self, key: &RedisKey, elements: V, ) -> CustomResult<(), errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send, V::Error: Into<fred::error::RedisError> + Send, { self.pool .rpush(key.tenant_aware_key(self), elements) .await .change_context(errors::RedisError::AppendElementsToListFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_elements( &self, key: &RedisKey, start: i64, stop: i64, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool .lrange(key.tenant_aware_key(self), start, stop) .await .change_context(errors::RedisError::GetListElementsFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> { self.pool .llen(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetListLengthFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn lpop_list_elements( &self, key: &RedisKey, count: Option<usize>, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool .lpop(key.tenant_aware_key(self), count) .await .change_context(errors::RedisError::PopListElementsFailed) } // Consumer Group API #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_create( &self, stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<(), errors::RedisError> { if matches!( id, RedisEntryId::AutoGeneratedID | RedisEntryId::UndeliveredEntryID ) { // FIXME: Replace with utils::when Err(errors::RedisError::InvalidRedisEntryId)?; } self.pool .xgroup_create(stream.tenant_aware_key(self), group, id, true) .await .change_context(errors::RedisError::ConsumerGroupCreateFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_destroy( &self, stream: &RedisKey, group: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool .xgroup_destroy(stream.tenant_aware_key(self), group) .await .change_context(errors::RedisError::ConsumerGroupDestroyFailed) } // the number of pending messages that the consumer had before it was deleted #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_delete_consumer( &self, stream: &RedisKey, group: &str, consumer: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool .xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer) .await .change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_set_last_id( &self, stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<String, errors::RedisError> { self.pool .xgroup_setid(stream.tenant_aware_key(self), group, id) .await .change_context(errors::RedisError::ConsumerGroupSetIdFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_set_message_owner<Ids, R>( &self, stream: &RedisKey, group: &str, consumer: &str, min_idle_time: u64, ids: Ids, ) -> CustomResult<R, errors::RedisError> where Ids: Into<MultipleIDs> + Debug + Send + Sync, R: FromRedis + Unpin + Send + 'static, { self.pool .xclaim( stream.tenant_aware_key(self), group, consumer, min_idle_time, ids, None, None, None, false, false, ) .await .change_context(errors::RedisError::ConsumerGroupClaimFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn evaluate_redis_script<V, T>( &self, lua_script: &'static str, key: Vec<String>, values: V, ) -> CustomResult<T, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, T: serde::de::DeserializeOwned + FromRedis, { let val: T = self .pool .eval(lua_script, key, values) .await .change_context(errors::RedisError::IncrementHashFieldFailed)?; Ok(val) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_multiple_keys_if_not_exists_and_get_values<V>( &self, keys: &[(RedisKey, V)], ttl: Option<i64>, ) -> CustomResult<Vec<SetGetReply<V>>, errors::RedisError> where V: TryInto<RedisValue> + Debug + FromRedis + ToOwned<Owned = V> + Send + Sync + serde::de::DeserializeOwned, V::Error: Into<fred::error::RedisError> + Send + Sync, { let futures = keys.iter().map(|(key, value)| { self.set_key_if_not_exists_and_get_value(key, (*value).to_owned(), ttl) }); let del_result = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::SetFailed)?; Ok(del_result) } /// Sets a value in Redis if not already present, and returns the value (either existing or newly set). /// This operation is atomic using Redis transactions. #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_if_not_exists_and_get_value<V>( &self, key: &RedisKey, value: V, ttl: Option<i64>, ) -> CustomResult<SetGetReply<V>, errors::RedisError> where V: TryInto<RedisValue> + Debug + FromRedis + Send + Sync + serde::de::DeserializeOwned, V::Error: Into<fred::error::RedisError> + Send + Sync, { let redis_key = key.tenant_aware_key(self); let ttl_seconds = ttl.unwrap_or(self.config.default_ttl.into()); // Get a client from the pool and start transaction let trx = self.get_transaction(); // Try to set if not exists with expiry - queue the command trx.set::<(), _, _>( &redis_key, value, Some(Expiration::EX(ttl_seconds)), Some(SetOptions::NX), false, ) .await .change_context(errors::RedisError::SetFailed) .attach_printable("Failed to queue set command")?; // Always get the value after the SET attempt - queue the command trx.get::<V, _>(&redis_key) .await .change_context(errors::RedisError::GetFailed) .attach_printable("Failed to queue get command")?; // Execute transaction let mut results: Vec<RedisValue> = trx .exec(true) .await .change_context(errors::RedisError::SetFailed) .attach_printable("Failed to execute the redis transaction")?; let msg = "Got unexpected number of results from transaction"; let get_result = results .pop() .ok_or(errors::RedisError::SetFailed) .attach_printable(msg)?; let set_result = results .pop() .ok_or(errors::RedisError::SetFailed) .attach_printable(msg)?; // Parse the GET result to get the actual value let actual_value: V = FromRedis::from_value(get_result) .change_context(errors::RedisError::SetFailed) .attach_printable("Failed to convert from redis value")?; // Check if SET NX succeeded or failed match set_result { // SET NX returns "OK" if key was set RedisValue::String(_) => Ok(SetGetReply::ValueSet(actual_value)), // SET NX returns null if key already exists RedisValue::Null => Ok(SetGetReply::ValueExists(actual_value)), _ => Err(report!(errors::RedisError::SetFailed)) .attach_printable("Unexpected result from SET NX operation"), } } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] use std::collections::HashMap; use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings}; #[tokio::test] async fn test_consumer_group_create() { let is_invalid_redis_entry_error = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let redis_conn = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // Act let result1 = redis_conn .consumer_group_create(&"TEST1".into(), "GTEST", &RedisEntryId::AutoGeneratedID) .await; let result2 = redis_conn .consumer_group_create( &"TEST3".into(), "GTEST", &RedisEntryId::UndeliveredEntryID, ) .await; // Assert Setup *result1.unwrap_err().current_context() == RedisError::InvalidRedisEntryId && *result2.unwrap_err().current_context() == RedisError::InvalidRedisEntryId }) }) .await .expect("Spawn block failure"); assert!(is_invalid_redis_entry_error); } #[tokio::test] async fn test_delete_existing_key_success() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let _ = pool.set_key(&"key".into(), "value".to_string()).await; // Act let result = pool.delete_key(&"key".into()).await; // Assert setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_delete_non_existing_key_success() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // Act let result = pool.delete_key(&"key not exists".into()).await; // Assert Setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_setting_keys_using_scripts() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let lua_script = r#" for i = 1, #KEYS do redis.call("INCRBY", KEYS[i], ARGV[i]) end return "#; let mut keys_and_values = HashMap::new(); for i in 0..10 { keys_and_values.insert(format!("key{i}"), i); } let key = keys_and_values.keys().cloned().collect::<Vec<_>>(); let values = keys_and_values .values() .map(|val| val.to_string()) .collect::<Vec<String>>(); // Act let result = pool .evaluate_redis_script::<_, ()>(lua_script, key, values) .await; // Assert Setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_getting_keys_using_scripts() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // First set some keys for i in 0..3 { let key = format!("script_test_key{i}").into(); let _ = pool.set_key(&key, format!("value{i}")).await; } let lua_script = r#" local results = {} for i = 1, #KEYS do results[i] = redis.call("GET", KEYS[i]) end return results "#; let keys = vec![ "script_test_key0".to_string(), "script_test_key1".to_string(), "script_test_key2".to_string(), ]; // Act let result = pool .evaluate_redis_script::<_, Vec<String>>(lua_script, keys, vec![""]) .await; // Assert Setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_new_key() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key = "test_new_key_string".into(); let value = "test_value".to_string(); // Act let result = pool .set_key_if_not_exists_and_get_value(&key, value.clone(), Some(30)) .await; // Assert match result { Ok(crate::types::SetGetReply::ValueSet(returned_value)) => { returned_value == value } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_existing_key() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key = "test_existing_key_string".into(); let initial_value = "initial_value".to_string(); let new_value = "new_value".to_string(); // First, set an initial value using regular set_key let _ = pool.set_key(&key, initial_value.clone()).await; // Act - try to set a new value (should fail and return existing value) let result = pool .set_key_if_not_exists_and_get_value(&key, new_value, Some(30)) .await; // Assert match result { Ok(crate::types::SetGetReply::ValueExists(returned_value)) => { returned_value == initial_value } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_with_default_ttl() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key = "test_default_ttl_key_string".into(); let value = "test_value".to_string(); // Act - use None for TTL to test default behavior let result = pool .set_key_if_not_exists_and_get_value(&key, value.clone(), None) .await; // Assert match result { Ok(crate::types::SetGetReply::ValueSet(returned_value)) => { returned_value == value } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_concurrent_access() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key_name = "test_concurrent_key_string"; let value1 = "value1".to_string(); let value2 = "value2".to_string(); // Act - simulate concurrent access let pool1 = pool.clone(""); let pool2 = pool.clone(""); let key1 = key_name.into(); let key2 = key_name.into(); let (result1, result2) = tokio::join!( pool1.set_key_if_not_exists_and_get_value(&key1, value1, Some(30)), pool2.set_key_if_not_exists_and_get_value(&key2, value2, Some(30)) ); // Assert - one should succeed with ValueSet, one should fail with ValueExists let result1_is_set = matches!(result1, Ok(crate::types::SetGetReply::ValueSet(_))); let result2_is_set = matches!(result2, Ok(crate::types::SetGetReply::ValueSet(_))); let result1_is_exists = matches!(result1, Ok(crate::types::SetGetReply::ValueExists(_))); let result2_is_exists = matches!(result2, Ok(crate::types::SetGetReply::ValueExists(_))); // Exactly one should be ValueSet and one should be ValueExists (result1_is_set && result2_is_exists) || (result1_is_exists && result2_is_set) }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_multiple_keys_success() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // Set up test data let keys = vec![ "multi_test_key1".into(), "multi_test_key2".into(), "multi_test_key3".into(), ]; let values = ["value1", "value2", "value3"]; // Set the keys for (key, value) in keys.iter().zip(values.iter()) { let _ = pool.set_key(key, value.to_string()).await; } // Act let result = pool.get_multiple_keys::<String>(&keys).await; // Assert match result { Ok(retrieved_values) => { retrieved_values.len() == 3 && retrieved_values.first() == Some(&Some("value1".to_string())) && retrieved_values.get(1) == Some(&Some("value2".to_string())) && retrieved_values.get(2) == Some(&Some("value3".to_string())) } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_multiple_keys_with_missing_keys() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let keys = vec![ "existing_key".into(), "non_existing_key".into(), "another_existing_key".into(), ]; // Set only some keys let _ = pool .set_key( keys.first().expect("should not be none"), "value1".to_string(), ) .await; let _ = pool .set_key( keys.get(2).expect("should not be none"), "value3".to_string(), ) .await; // Act let result = pool.get_multiple_keys::<String>(&keys).await; // Assert match result { Ok(retrieved_values) => { retrieved_values.len() == 3 && *retrieved_values.first().expect("should not be none") == Some("value1".to_string()) && retrieved_values.get(1).is_some_and(|v| v.is_none()) && *retrieved_values.get(2).expect("should not be none") == Some("value3".to_string()) } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_multiple_keys_empty_input() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let keys: Vec<crate::types::RedisKey> = vec![]; // Act let result = pool.get_multiple_keys::<String>(&keys).await; // Assert match result { Ok(retrieved_values) => retrieved_values.is_empty(), _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_and_deserialize_multiple_keys() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, Clone)] struct TestData { id: u32, name: String, } let test_data = [ TestData { id: 1, name: "test1".to_string(), }, TestData { id: 2, name: "test2".to_string(), }, ]; let keys = vec![ "serialize_test_key1".into(), "serialize_test_key2".into(), "non_existing_serialize_key".into(), ]; // Set serialized data for first two keys for (i, data) in test_data.iter().enumerate() { let _ = pool .serialize_and_set_key(keys.get(i).expect("should not be none"), data) .await; } // Act let result = pool .get_and_deserialize_multiple_keys::<TestData>(&keys, "TestData") .await; // Assert match result { Ok(retrieved_data) => { retrieved_data.len() == 3 && retrieved_data.first() == Some(&Some(test_data[0].clone())) && retrieved_data.get(1) == Some(&Some(test_data[1].clone())) && retrieved_data.get(2) == Some(&None) } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } }
{ "crate": "redis_interface", "file": "crates/redis_interface/src/commands.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_events_-1574145251741928287
clm
file
// Repository: hyperswitch // Crate: events // File: crates/events/src/lib.rs // Contains: 1 structs, 1 enums #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))] #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] //! A generic event handler system. //! This library consists of 4 parts: //! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database. //! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event. //! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events. //! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier. mod actix; use std::{collections::HashMap, sync::Arc}; use error_stack::{Result, ResultExt}; use masking::{ErasedMaskSerialize, Serialize}; use router_env::logger; use serde::Serializer; use serde_json::Value; use time::PrimitiveDateTime; /// Errors that can occur when working with events. #[derive(Debug, Clone, thiserror::Error)] pub enum EventsError { /// An error occurred when publishing the event. #[error("Generic Error")] GenericError, /// An error occurred when serializing the event. #[error("Event serialization error")] SerializationError, /// An error occurred when publishing/producing the event. #[error("Event publishing error")] PublishError, } /// An event that can be published. pub trait Event: EventInfo { /// The type of the event. type EventType; /// The timestamp of the event. fn timestamp(&self) -> PrimitiveDateTime; /// The (unique) identifier of the event. fn identifier(&self) -> String; /// The class/type of the event. This is used to group/categorize events together. fn class(&self) -> Self::EventType; /// Metadata associated with the event fn metadata(&self) -> HashMap<String, String> { HashMap::new() } } /// Hold the context information for any events #[derive(Clone)] pub struct EventContext<T, A> where A: MessagingInterface<MessageClass = T>, { message_sink: Arc<A>, metadata: HashMap<String, Value>, } /// intermediary structure to build events with in-place info. #[must_use = "make sure to call `emit` or `try_emit` to actually emit the event"] pub struct EventBuilder<T, A, E, D> where A: MessagingInterface<MessageClass = T>, E: Event<EventType = T, Data = D>, { message_sink: Arc<A>, metadata: HashMap<String, Value>, event: E, } /// A flattened event that flattens the context provided to it along with the actual event. struct FlatMapEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A); impl<T, A, E, D> EventBuilder<T, A, E, D> where A: MessagingInterface<MessageClass = T>, E: Event<EventType = T, Data = D>, { /// Add metadata to the event. pub fn with<F: ErasedMaskSerialize, G: EventInfo<Data = F> + 'static>( mut self, info: G, ) -> Self { info.data() .and_then(|i| { i.masked_serialize() .change_context(EventsError::SerializationError) }) .map_err(|e| { logger::error!("Error adding event info: {:?}", e); }) .ok() .and_then(|data| self.metadata.insert(info.key(), data)); self } /// Emit the event and log any errors. pub fn emit(self) { self.try_emit() .map_err(|e| { logger::error!("Error emitting event: {:?}", e); }) .ok(); } /// Emit the event. pub fn try_emit(self) -> Result<(), EventsError> { let ts = self.event.timestamp(); let metadata = self.event.metadata(); self.message_sink .send_message(FlatMapEvent(self.metadata, self.event), metadata, ts) } } impl<T, A> Serialize for FlatMapEvent<T, A> where A: Event<EventType = T>, { fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> where S: Serializer, { let mut serialize_map: HashMap<_, _> = self .0 .iter() .filter_map(|(k, v)| Some((k.clone(), v.masked_serialize().ok()?))) .collect(); match self.1.data().map(|i| i.masked_serialize()) { Ok(Ok(Value::Object(map))) => { for (k, v) in map.into_iter() { serialize_map.insert(k, v); } } Ok(Ok(i)) => { serialize_map.insert(self.1.key(), i); } i => { logger::error!("Error serializing event: {:?}", i); } }; serialize_map.serialize(serializer) } } impl<T, A> EventContext<T, A> where A: MessagingInterface<MessageClass = T>, { /// Create a new event context. pub fn new(message_sink: A) -> Self { Self { message_sink: Arc::new(message_sink), metadata: HashMap::new(), } } /// Add metadata to the event context. #[track_caller] pub fn record_info<G: ErasedMaskSerialize, E: EventInfo<Data = G> + 'static>( &mut self, info: E, ) { match info.data().and_then(|i| { i.masked_serialize() .change_context(EventsError::SerializationError) }) { Ok(data) => { self.metadata.insert(info.key(), data); } Err(e) => { logger::error!("Error recording event info: {:?}", e); } } } /// Emit an event. pub fn try_emit<E: Event<EventType = T>>(&self, event: E) -> Result<(), EventsError> { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } .try_emit() } /// Emit an event. pub fn emit<D, E: Event<EventType = T, Data = D>>(&self, event: E) { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } .emit() } /// Create an event builder. pub fn event<D, E: Event<EventType = T, Data = D>>( &self, event: E, ) -> EventBuilder<T, A, E, D> { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } } } /// Add information/metadata to the current context of an event. pub trait EventInfo { /// The data that is sent with the event. type Data: ErasedMaskSerialize; /// The data that is sent with the event. fn data(&self) -> Result<Self::Data, EventsError>; /// The key identifying the data for an event. fn key(&self) -> String; } impl EventInfo for (String, String) { type Data = String; fn data(&self) -> Result<String, EventsError> { Ok(self.1.clone()) } fn key(&self) -> String { self.0.clone() } } /// A messaging interface for sending messages/events. /// This can be implemented for any messaging system, such as a message queue, a logger, or a database. pub trait MessagingInterface { /// The type of the event used for categorization by the event publisher. type MessageClass; /// Send a message that follows the defined message class. fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize; } /// A message that can be sent. pub trait Message { /// The type of the event used for categorization by the event publisher. type Class; /// The type of the event used for categorization by the event publisher. fn get_message_class(&self) -> Self::Class; /// The (unique) identifier of the event. fn identifier(&self) -> String; } impl<T, A> Message for FlatMapEvent<T, A> where A: Event<EventType = T>, { type Class = T; fn get_message_class(&self) -> Self::Class { self.1.class() } fn identifier(&self) -> String { self.1.identifier() } }
{ "crate": "events", "file": "crates/events/src/lib.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_payment_methods_-972847150711255517
clm
file
// Repository: hyperswitch // Crate: payment_methods // File: crates/payment_methods/src/controller.rs // Contains: 1 structs, 1 enums use std::fmt::Debug; #[cfg(feature = "payouts")] use api_models::payouts; use api_models::{enums as api_enums, payment_methods as api}; #[cfg(feature = "v1")] use common_enums::enums as common_enums; #[cfg(feature = "v2")] use common_utils::encryption; use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::payment_methods::PaymentMethodVaultSourceDetails; use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption}; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] use scheduler::errors as sch_errors; use serde::{Deserialize, Serialize}; use storage_impl::{errors as storage_errors, payment_method}; use crate::core::errors; #[derive(Debug, Deserialize, Serialize)] pub struct DeleteCardResp { pub status: String, pub error_message: Option<String>, pub error_code: Option<String>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DataDuplicationCheck { Duplicated, MetaDataChanged, } #[async_trait::async_trait] pub trait PaymentMethodsController { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn create_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: &str, locker_id: Option<String>, merchant_id: &id_type::MerchantId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, payment_method_data: crypto::OptionalEncryptableValue, connector_mandate_details: Option<serde_json::Value>, status: Option<common_enums::PaymentMethodStatus>, network_transaction_id: Option<String>, payment_method_billing_address: crypto::OptionalEncryptableValue, card_scheme: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn insert_payment_method( &self, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, payment_method_billing_address: crypto::OptionalEncryptableValue, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn insert_payment_method( &self, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, payment_method_billing_address: Option<encryption::Encryption>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] async fn add_payment_method( &self, req: &api::PaymentMethodCreate, ) -> errors::PmResponse<api::PaymentMethodResponse>; #[cfg(feature = "v1")] async fn retrieve_payment_method( &self, pm: api::PaymentMethodId, ) -> errors::PmResponse<api::PaymentMethodResponse>; #[cfg(feature = "v1")] async fn delete_payment_method( &self, pm_id: api::PaymentMethodId, ) -> errors::PmResponse<api::PaymentMethodDeleteResponse>; async fn add_card_hs( &self, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, locker_choice: api_enums::LockerChoice, card_reference: Option<&str>, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method async fn add_card_to_locker( &self, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, card_reference: Option<&str>, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; #[cfg(feature = "payouts")] async fn add_bank_to_locker( &self, req: api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, bank: &payouts::Bank, customer_id: &id_type::CustomerId, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; #[cfg(feature = "v1")] async fn get_or_insert_payment_method( &self, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, customer_id: &id_type::CustomerId, key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] async fn get_or_insert_payment_method( &self, _req: api::PaymentMethodCreate, _resp: &mut api::PaymentMethodResponse, _customer_id: &id_type::CustomerId, _key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod> { todo!() } #[cfg(feature = "v1")] async fn get_card_details_with_locker_fallback( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<Option<api::CardDetailFromLocker>>; #[cfg(feature = "v1")] async fn get_card_details_without_locker_fallback( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<api::CardDetailFromLocker>; async fn delete_card_from_locker( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::PmResult<DeleteCardResp>; #[cfg(feature = "v1")] fn store_default_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>); #[cfg(feature = "v2")] fn store_default_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>); #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn save_network_token_and_update_payment_method( &self, req: &api::PaymentMethodMigrate, key_store: &merchant_key_store::MerchantKeyStore, network_token_data: &api_models::payment_methods::MigrateNetworkTokenData, network_token_requestor_ref_id: String, pm_id: String, ) -> errors::PmResult<bool>; #[cfg(feature = "v1")] async fn set_default_payment_method( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, payment_method_id: String, ) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>; #[cfg(feature = "v1")] async fn add_payment_method_status_update_task( &self, payment_method: &payment_methods::PaymentMethod, prev_status: common_enums::PaymentMethodStatus, curr_status: common_enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, ) -> Result<(), sch_errors::ProcessTrackerError>; #[cfg(feature = "v1")] async fn validate_merchant_connector_ids_in_connector_mandate_details( &self, key_store: &merchant_key_store::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::CommonMandateReference, merchant_id: &id_type::MerchantId, card_network: Option<common_enums::CardNetwork>, ) -> errors::PmResult<()>; #[cfg(feature = "v1")] async fn get_card_details_from_locker( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<api::CardDetailFromLocker>; } pub async fn create_encrypted_data<T>( key_manager_state: &keymanager::KeyManagerState, key_store: &merchant_key_store::MerchantKeyStore, data: T, ) -> Result< crypto::Encryptable<Secret<serde_json::Value>>, error_stack::Report<storage_errors::StorageError>, > where T: Debug + Serialize, { let key = key_store.key.get_inner().peek(); let identifier = keymanager::Identifier::Merchant(key_store.merchant_id.clone()); let encoded_data = ext_traits::Encode::encode_to_value(&data) .change_context(storage_errors::StorageError::SerializationFailed) .attach_printable("Unable to encode data")?; let secret_data = Secret::<_, masking::WithType>::new(encoded_data); let encrypted_data = type_encryption::crypto_operation( key_manager_state, type_name!(payment_method::PaymentMethod), type_encryption::CryptoOperation::Encrypt(secret_data), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .change_context(storage_errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) }
{ "crate": "payment_methods", "file": "crates/payment_methods/src/controller.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_payment_methods_2549204059160007966
clm
file
// Repository: hyperswitch // Crate: payment_methods // File: crates/payment_methods/src/state.rs // Contains: 1 structs, 0 enums #[cfg(feature = "v1")] use common_utils::errors::CustomResult; use common_utils::types::keymanager; #[cfg(feature = "v1")] use hyperswitch_domain_models::merchant_account; use hyperswitch_domain_models::{ cards_info, customer, merchant_key_store, payment_methods as pm_domain, }; use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore}; #[async_trait::async_trait] pub trait PaymentMethodsStorageInterface: Send + Sync + dyn_clone::DynClone + pm_domain::PaymentMethodInterface<Error = errors::StorageError> + cards_info::CardsInfoInterface<Error = errors::StorageError> + customer::CustomerInterface<Error = errors::StorageError> + 'static { } dyn_clone::clone_trait_object!(PaymentMethodsStorageInterface); #[async_trait::async_trait] impl PaymentMethodsStorageInterface for MockDb {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for RouterStore<T> {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for KVRouterStore<T> {} #[derive(Clone)] pub struct PaymentMethodsState { pub store: Box<dyn PaymentMethodsStorageInterface>, pub key_store: Option<merchant_key_store::MerchantKeyStore>, pub key_manager_state: keymanager::KeyManagerState, } impl From<&PaymentMethodsState> for keymanager::KeyManagerState { fn from(state: &PaymentMethodsState) -> Self { state.key_manager_state.clone() } } #[cfg(feature = "v1")] impl PaymentMethodsState { pub async fn find_payment_method( &self, key_store: &merchant_key_store::MerchantKeyStore, merchant_account: &merchant_account::MerchantAccount, payment_method_id: String, ) -> CustomResult<pm_domain::PaymentMethod, errors::StorageError> { let db = &*self.store; let key_manager_state = &(self.key_manager_state).clone(); match db .find_payment_method( key_manager_state, key_store, &payment_method_id, merchant_account.storage_scheme, ) .await { Err(err) if err.current_context().is_db_not_found() => { db.find_payment_method_by_locker_id( key_manager_state, key_store, &payment_method_id, merchant_account.storage_scheme, ) .await } Ok(pm) => Ok(pm), Err(err) => Err(err), } } }
{ "crate": "payment_methods", "file": "crates/payment_methods/src/state.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_payment_methods_5002721337420001288
clm
file
// Repository: hyperswitch // Crate: payment_methods // File: crates/payment_methods/src/core/migration.rs // Contains: 3 structs, 0 enums use actix_multipart::form::{self, bytes, text}; use api_models::payment_methods as pm_api; use csv::Reader; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::{api, merchant_context}; use masking::PeekInterface; use rdkafka::message::ToBytes; use router_env::{instrument, tracing}; use crate::core::errors; #[cfg(feature = "v1")] use crate::{controller as pm, state}; pub mod payment_methods; pub use payment_methods::migrate_payment_method; #[cfg(feature = "v1")] type PmMigrationResult<T> = errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>; #[cfg(feature = "v1")] pub async fn migrate_payment_methods( state: &state::PaymentMethodsState, payment_methods: Vec<pm_api::PaymentMethodRecord>, merchant_id: &common_utils::id_type::MerchantId, merchant_context: &merchant_context::MerchantContext, mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, controller: &dyn pm::PaymentMethodsController, ) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> { let mut result = Vec::with_capacity(payment_methods.len()); for record in payment_methods { let req = pm_api::PaymentMethodMigrate::try_from(( &record, merchant_id.clone(), mca_ids.as_ref(), )) .map_err(|err| errors::ApiErrorResponse::InvalidRequestData { message: format!("error: {err:?}"), }) .attach_printable("record deserialization failed"); let res = match req { Ok(migrate_request) => { let res = migrate_payment_method( state, migrate_request, merchant_id, merchant_context, controller, ) .await; match res { Ok(api::ApplicationResponse::Json(response)) => Ok(response), Err(e) => Err(e.to_string()), _ => Err("Failed to migrate payment method".to_string()), } } Err(e) => Err(e.to_string()), }; result.push(pm_api::PaymentMethodMigrationResponse::from((res, record))); } Ok(api::ApplicationResponse::Json(result)) } #[derive(Debug, form::MultipartForm)] pub struct PaymentMethodsMigrateForm { #[multipart(limit = "1MB")] pub file: bytes::Bytes, pub merchant_id: text::Text<common_utils::id_type::MerchantId>, pub merchant_connector_id: Option<text::Text<common_utils::id_type::MerchantConnectorAccountId>>, pub merchant_connector_ids: Option<text::Text<String>>, } pub struct MerchantConnectorValidator; impl MerchantConnectorValidator { pub fn parse_comma_separated_ids( ids_string: &str, ) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse> { // Estimate capacity based on comma count let capacity = ids_string.matches(',').count() + 1; let mut result = Vec::with_capacity(capacity); for id in ids_string.split(',') { let trimmed_id = id.trim(); if !trimmed_id.is_empty() { let mca_id = common_utils::id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string()) .map_err(|_| errors::ApiErrorResponse::InvalidRequestData { message: format!("Invalid merchant_connector_account_id: {trimmed_id}"), })?; result.push(mca_id); } } Ok(result) } fn validate_form_csv_conflicts( records: &[pm_api::PaymentMethodRecord], form_has_single_id: bool, form_has_multiple_ids: bool, ) -> Result<(), errors::ApiErrorResponse> { if form_has_single_id { // If form has merchant_connector_id, CSV records should not have merchant_connector_ids for (index, record) in records.iter().enumerate() { if record.merchant_connector_ids.is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Record at line {} has merchant_connector_ids but form has merchant_connector_id. Only one should be provided", index + 1 ), }); } } } if form_has_multiple_ids { // If form has merchant_connector_ids, CSV records should not have merchant_connector_id for (index, record) in records.iter().enumerate() { if record.merchant_connector_id.is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Record at line {} has merchant_connector_id but form has merchant_connector_ids. Only one should be provided", index + 1 ), }); } } } Ok(()) } } type MigrationValidationResult = Result< ( common_utils::id_type::MerchantId, Vec<pm_api::PaymentMethodRecord>, Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ), errors::ApiErrorResponse, >; impl PaymentMethodsMigrateForm { pub fn validate_and_get_payment_method_records(self) -> MigrationValidationResult { // Step 1: Validate form-level conflicts let form_has_single_id = self.merchant_connector_id.is_some(); let form_has_multiple_ids = self.merchant_connector_ids.is_some(); if form_has_single_id && form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Both merchant_connector_id and merchant_connector_ids cannot be provided" .to_string(), }); } // Ensure at least one is provided if !form_has_single_id && !form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Either merchant_connector_id or merchant_connector_ids must be provided" .to_string(), }); } // Step 2: Parse CSV let records = parse_csv(self.file.data.to_bytes()).map_err(|e| { errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), } })?; // Step 3: Validate CSV vs Form conflicts MerchantConnectorValidator::validate_form_csv_conflicts( &records, form_has_single_id, form_has_multiple_ids, )?; // Step 4: Prepare the merchant connector account IDs for return let mca_ids = if let Some(ref single_id) = self.merchant_connector_id { Some(vec![(**single_id).clone()]) } else if let Some(ref ids_string) = self.merchant_connector_ids { let parsed_ids = MerchantConnectorValidator::parse_comma_separated_ids(ids_string)?; if parsed_ids.is_empty() { None } else { Some(parsed_ids) } } else { None }; // Step 5: Return the updated structure Ok((self.merchant_id.clone(), records, mca_ids)) } } fn parse_csv(data: &[u8]) -> csv::Result<Vec<pm_api::PaymentMethodRecord>> { let mut csv_reader = Reader::from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for result in csv_reader.deserialize() { let mut record: pm_api::PaymentMethodRecord = result?; id_counter += 1; record.line_number = Some(id_counter); records.push(record); } Ok(records) } #[instrument(skip_all)] pub fn validate_card_expiry( card_exp_month: &masking::Secret<String>, card_exp_year: &masking::Secret<String>, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { let exp_month = card_exp_month .peek() .to_string() .parse::<u8>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_month", })?; ::cards::CardExpirationMonth::try_from(exp_month).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Month".to_string(), }, )?; let year_str = card_exp_year.peek().to_string(); validate_card_exp_year(year_str).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Year".to_string(), }, )?; Ok(()) } fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> { let year_str = year.to_string(); if year_str.len() == 2 || year_str.len() == 4 { year_str .parse::<u16>() .map_err(|_| errors::ValidationError::InvalidValue { message: "card_exp_year".to_string(), })?; Ok(()) } else { Err(errors::ValidationError::InvalidValue { message: "invalid card expiration year".to_string(), }) } } #[derive(Debug)] pub struct RecordMigrationStatus { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, } #[derive(Debug)] pub struct RecordMigrationStatusBuilder { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, } impl RecordMigrationStatusBuilder { pub fn new() -> Self { Self { card_migrated: None, network_token_migrated: None, connector_mandate_details_migrated: None, network_transaction_migrated: None, } } pub fn card_migrated(&mut self, card_migrated: bool) { self.card_migrated = Some(card_migrated); } pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) { self.network_token_migrated = network_token_migrated; } pub fn connector_mandate_details_migrated( &mut self, connector_mandate_details_migrated: Option<bool>, ) { self.connector_mandate_details_migrated = connector_mandate_details_migrated; } pub fn network_transaction_id_migrated(&mut self, network_transaction_migrated: Option<bool>) { self.network_transaction_migrated = network_transaction_migrated; } pub fn build(self) -> RecordMigrationStatus { RecordMigrationStatus { card_migrated: self.card_migrated, network_token_migrated: self.network_token_migrated, connector_mandate_details_migrated: self.connector_mandate_details_migrated, network_transaction_migrated: self.network_transaction_migrated, } } } impl Default for RecordMigrationStatusBuilder { fn default() -> Self { Self::new() } }
{ "crate": "payment_methods", "file": "crates/payment_methods/src/core/migration.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_payment_methods_-8217620927264925469
clm
file
// Repository: hyperswitch // Crate: payment_methods // File: crates/payment_methods/src/configs/settings.rs // Contains: 14 structs, 0 enums use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::errors::CustomResult; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use masking::Secret; use serde::{self, Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, Clone)] #[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payment_required_fields.toml pub struct RequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PaymentMethodType(pub HashMap<enums::PaymentMethodType, ConnectorFields>); #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ConnectorFields { pub fields: HashMap<enums::Connector, RequiredFieldFinal>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>); #[derive(Debug, Deserialize, Clone)] pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); #[derive(Debug, Deserialize, Clone)] pub struct BanksVector { #[serde(deserialize_with = "deserialize_hashset")] pub banks: HashSet<common_enums::enums::BankNames>, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: HashMap<String, RequiredFieldInfo>, pub non_mandate: HashMap<String, RequiredFieldInfo>, pub common: HashMap<String, RequiredFieldInfo>, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: Option<Vec<RequiredFieldInfo>>, pub non_mandate: Option<Vec<RequiredFieldInfo>>, pub common: Option<Vec<RequiredFieldInfo>>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodAuth { pub redis_expiry: i64, pub pm_auth_key: Secret<String>, } #[async_trait::async_trait] impl SecretsHandler for PaymentMethodAuth { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let payment_method_auth = value.get_inner(); let pm_auth_key = secret_management_client .get_secret(payment_method_auth.pm_auth_key.clone()) .await?; Ok(value.transition_state(|payment_method_auth| Self { pm_auth_key, ..payment_method_auth })) } } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct EligiblePaymentMethods { #[serde(deserialize_with = "deserialize_hashset")] pub sdk_eligible_payment_methods: HashSet<String>, } #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodsForMandate( pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>, ); #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodTypesForMandate( pub HashMap<enums::PaymentMethodType, SupportedConnectorsForMandate>, ); #[derive(Debug, Deserialize, Clone)] pub struct SupportedConnectorsForMandate { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone)] pub struct Mandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, pub update_mandate_supported: SupportedPaymentMethodsForMandate, } #[derive(Debug, Deserialize, Clone)] pub struct ZeroMandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, } fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { T::from_str(s.trim()).map_err(|error| { format!( "Unable to deserialize `{}` as `{}`: {error}", s.trim(), std::any::type_name::<T>() ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) }
{ "crate": "payment_methods", "file": "crates/payment_methods/src/configs/settings.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 14, "num_tables": null, "score": null, "total_crates": null }
file_pm_auth_3569401708933910686
clm
file
// Repository: hyperswitch // Crate: pm_auth // File: crates/pm_auth/src/types.rs // Contains: 19 structs, 6 enums pub mod api; use std::marker::PhantomData; use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate}; use api_models::enums as api_enums; use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType}; use common_utils::{id_type, types}; use masking::Secret; #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { pub flow: PhantomData<F>, pub merchant_id: Option<id_type::MerchantId>, pub connector: Option<String>, pub request: Request, pub response: Result<Response, ErrorResponse>, pub connector_auth_type: ConnectorAuthType, pub connector_http_status_code: Option<u16>, } #[derive(Debug, Clone)] pub struct LinkTokenRequest { pub client_name: String, pub country_codes: Option<Vec<String>>, pub language: Option<String>, pub user_info: Option<id_type::CustomerId>, pub client_platform: Option<api_enums::ClientPlatform>, pub android_package_name: Option<String>, pub redirect_uri: Option<String>, } #[derive(Debug, Clone)] pub struct LinkTokenResponse { pub link_token: String, } pub type LinkTokenRouterData = PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>; #[derive(Debug, Clone)] pub struct ExchangeTokenRequest { pub public_token: String, } #[derive(Debug, Clone)] pub struct ExchangeTokenResponse { pub access_token: String, } impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse { fn from(value: ExchangeTokenResponse) -> Self { Self { access_token: value.access_token, } } } pub type ExchangeTokenRouterData = PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; #[derive(Debug, Clone)] pub struct BankAccountCredentialsRequest { pub access_token: Secret<String>, pub optional_ids: Option<BankAccountOptionalIDs>, } #[derive(Debug, Clone)] pub struct BankAccountOptionalIDs { pub ids: Vec<Secret<String>>, } #[derive(Debug, Clone)] pub struct BankAccountCredentialsResponse { pub credentials: Vec<BankAccountDetails>, } #[derive(Debug, Clone)] pub struct BankAccountDetails { pub account_name: Option<String>, pub account_details: PaymentMethodTypeDetails, pub payment_method_type: PaymentMethodType, pub payment_method: PaymentMethod, pub account_id: Secret<String>, pub account_type: Option<String>, pub balance: Option<types::FloatMajorUnit>, } #[derive(Debug, Clone)] pub enum PaymentMethodTypeDetails { Ach(BankAccountDetailsAch), Bacs(BankAccountDetailsBacs), Sepa(BankAccountDetailsSepa), } #[derive(Debug, Clone)] pub struct BankAccountDetailsAch { pub account_number: Secret<String>, pub routing_number: Secret<String>, } #[derive(Debug, Clone)] pub struct BankAccountDetailsBacs { pub account_number: Secret<String>, pub sort_code: Secret<String>, } #[derive(Debug, Clone)] pub struct BankAccountDetailsSepa { pub iban: Secret<String>, pub bic: Secret<String>, } pub type BankDetailsRouterData = PaymentAuthRouterData< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, >; #[derive(Debug, Clone)] pub struct RecipientCreateRequest { pub name: String, pub account_data: RecipientAccountData, pub address: Option<RecipientCreateAddress>, } #[derive(Debug, Clone)] pub struct RecipientCreateResponse { pub recipient_id: String, } #[derive(Debug, Clone)] pub enum RecipientAccountData { Iban(Secret<String>), Bacs { sort_code: Secret<String>, account_number: Secret<String>, }, FasterPayments { sort_code: Secret<String>, account_number: Secret<String>, }, Sepa(Secret<String>), SepaInstant(Secret<String>), Elixir { account_number: Secret<String>, iban: Secret<String>, }, Bankgiro(Secret<String>), Plusgiro(Secret<String>), } #[derive(Debug, Clone)] pub struct RecipientCreateAddress { pub street: String, pub city: String, pub postal_code: String, pub country: CountryAlpha2, } pub type RecipientCreateRouterData = PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; pub type PaymentAuthLinkTokenType = dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; pub type PaymentAuthExchangeTokenType = dyn api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, >; pub type PaymentInitiationRecipientCreateType = dyn api::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; #[derive(Clone, Debug, strum::EnumString, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodAuthConnectors { Plaid, } #[derive(Debug, Clone)] pub struct ResponseRouterData<Flow, R, Request, Response> { pub response: R, pub data: PaymentAuthRouterData<Flow, Request, Response>, pub http_code: u16, } #[derive(Clone, Debug, serde::Serialize)] pub struct ErrorResponse { pub code: String, pub message: String, pub reason: Option<String>, pub status_code: u16, } impl ErrorResponse { fn get_not_implemented() -> Self { Self { code: "IR_00".to_string(), message: "This API is under development and will be made available soon.".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub enum MerchantAccountData { Iban { iban: Secret<String>, name: String, }, Bacs { account_number: Secret<String>, sort_code: Secret<String>, name: String, }, FasterPayments { account_number: Secret<String>, sort_code: Secret<String>, name: String, }, Sepa { iban: Secret<String>, name: String, }, SepaInstant { iban: Secret<String>, name: String, }, Elixir { account_number: Secret<String>, iban: Secret<String>, name: String, }, Bankgiro { number: Secret<String>, name: String, }, Plusgiro { number: Secret<String>, name: String, }, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { ConnectorRecipientId(Secret<String>), WalletId(Secret<String>), AccountData(MerchantAccountData), } #[derive(Default, Debug, Clone, serde::Deserialize)] pub enum ConnectorAuthType { BodyKey { client_id: Secret<String>, secret: Secret<String>, }, #[default] NoKey, } #[derive(Clone, Debug)] pub struct Response { pub headers: Option<http::HeaderMap>, pub response: bytes::Bytes, pub status_code: u16, } #[derive(serde::Deserialize, Clone)] pub struct AuthServiceQueryParam { pub client_secret: Option<String>, }
{ "crate": "pm_auth", "file": "crates/pm_auth/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 6, "num_structs": 19, "num_tables": null, "score": null, "total_crates": null }
file_pm_auth_746554079114470275
clm
file
// Repository: hyperswitch // Crate: pm_auth // File: crates/pm_auth/src/types/api.rs // Contains: 1 structs, 0 enums pub mod auth_service; use std::fmt::Debug; use common_utils::{ errors::CustomResult, request::{Request, RequestContent}, }; use masking::Maskable; use crate::{ core::errors::ConnectorError, types::{ self as auth_types, api::auth_service::{AuthService, PaymentInitiation}, }, }; #[async_trait::async_trait] pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync { fn get_headers( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(vec![]) } fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } fn get_url( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<String, ConnectorError> { Ok(String::new()) } fn get_request_body( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, ) -> CustomResult<RequestContent, ConnectorError> { Ok(RequestContent::Json(Box::new(serde_json::json!(r#"{}"#)))) } fn build_request( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(None) } fn handle_response( &self, data: &super::PaymentAuthRouterData<T, Req, Resp>, _res: auth_types::Response, ) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError> where T: Clone, Req: Clone, Resp: Clone, { Ok(data.clone()) } fn get_error_response( &self, _res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { Ok(auth_types::ErrorResponse::get_not_implemented()) } fn get_5xx_error_response( &self, res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; Ok(auth_types::ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, }) } } pub trait ConnectorCommonExt<Flow, Req, Resp>: ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> { fn build_headers( &self, _req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(Vec::new()) } } pub type BoxedConnectorIntegration<'a, T, Req, Resp> = Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; } impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S where S: ConnectorIntegration<T, Req, Resp>, { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { Box::new(self) } } pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {} impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {} pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>; #[derive(Clone, Debug)] pub struct PaymentAuthConnectorData { pub connector: BoxedPaymentAuthConnector, pub connector_name: super::PaymentMethodAuthConnectors, } pub trait ConnectorCommon { fn id(&self) -> &'static str; fn get_auth_header( &self, _auth_type: &auth_types::ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(Vec::new()) } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str; fn build_error_response( &self, res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { Ok(auth_types::ErrorResponse { status_code: res.status_code, code: crate::consts::NO_ERROR_CODE.to_string(), message: crate::consts::NO_ERROR_MESSAGE.to_string(), reason: None, }) } }
{ "crate": "pm_auth", "file": "crates/pm_auth/src/types/api.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_pm_auth_7808154253284123069
clm
file
// Repository: hyperswitch // Crate: pm_auth // File: crates/pm_auth/src/types/api/auth_service.rs // Contains: 4 structs, 0 enums use crate::types::{ BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest, ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest, RecipientCreateResponse, }; pub trait AuthService: super::ConnectorCommon + AuthServiceLinkToken + AuthServiceExchangeToken + AuthServiceBankAccountCredentials { } pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {} #[derive(Debug, Clone)] pub struct LinkToken; pub trait AuthServiceLinkToken: super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse> { } #[derive(Debug, Clone)] pub struct ExchangeToken; pub trait AuthServiceExchangeToken: super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse> { } #[derive(Debug, Clone)] pub struct BankAccountCredentials; pub trait AuthServiceBankAccountCredentials: super::ConnectorIntegration< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, > { } #[derive(Debug, Clone)] pub struct RecipientCreate; pub trait PaymentInitiationRecipientCreate: super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse> { }
{ "crate": "pm_auth", "file": "crates/pm_auth/src/types/api/auth_service.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_pm_auth_-3000793074136996197
clm
file
// Repository: hyperswitch // Crate: pm_auth // File: crates/pm_auth/src/connector/plaid.rs // Contains: 1 structs, 0 enums pub mod transformers; use std::fmt::Debug; use common_utils::{ ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::ResultExt; use masking::{Mask, Maskable}; use transformers as plaid; use crate::{ core::errors, types::{ self as auth_types, api::{ auth_service::{ self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate, }, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, }, }, }; #[derive(Debug, Clone)] pub struct Plaid; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( "Content-Type".to_string(), self.get_content_type().to_string().into(), )]; let mut auth = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut auth); Ok(header) } } impl ConnectorCommon for Plaid { fn id(&self) -> &'static str { "plaid" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str { "https://sandbox.plaid.com" } fn get_auth_header( &self, auth_type: &auth_types::ConnectorAuthType, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = plaid::PlaidAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let client_id = auth.client_id.into_masked(); let secret = auth.secret.into_masked(); Ok(vec![ ("PLAID-CLIENT-ID".to_string(), client_id), ("PLAID-SECRET".to_string(), secret), ]) } fn build_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { let response: plaid::PlaidErrorResponse = res.response .parse_struct("PlaidErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(auth_types::ErrorResponse { status_code: res.status_code, code: crate::consts::NO_ERROR_CODE.to_string(), message: response.error_message, reason: response.display_message, }) } } impl auth_service::AuthService for Plaid {} impl auth_service::PaymentInitiationRecipientCreate for Plaid {} impl auth_service::PaymentInitiation for Plaid {} impl auth_service::AuthServiceLinkToken for Plaid {} impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse> for Plaid { fn get_headers( &self, req: &auth_types::LinkTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &auth_types::LinkTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "/link/token/create" )) } fn get_request_body( &self, req: &auth_types::LinkTokenRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::LinkTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentAuthLinkTokenType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(auth_types::PaymentAuthLinkTokenType::get_headers( self, req, connectors, )?) .set_body(auth_types::PaymentAuthLinkTokenType::get_request_body( self, req, )?) .build(), )) } fn handle_response( &self, data: &auth_types::LinkTokenRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> { let response: plaid::PlaidLinkTokenResponse = res .response .parse_struct("PlaidLinkTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; <auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } } impl auth_service::AuthServiceExchangeToken for Plaid {} impl ConnectorIntegration< ExchangeToken, auth_types::ExchangeTokenRequest, auth_types::ExchangeTokenResponse, > for Plaid { fn get_headers( &self, req: &auth_types::ExchangeTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &auth_types::ExchangeTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "/item/public_token/exchange" )) } fn get_request_body( &self, req: &auth_types::ExchangeTokenRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::ExchangeTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentAuthExchangeTokenType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(auth_types::PaymentAuthExchangeTokenType::get_headers( self, req, connectors, )?) .set_body(auth_types::PaymentAuthExchangeTokenType::get_request_body( self, req, )?) .build(), )) } fn handle_response( &self, data: &auth_types::ExchangeTokenRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> { let response: plaid::PlaidExchangeTokenResponse = res .response .parse_struct("PlaidExchangeTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; <auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } } impl auth_service::AuthServiceBankAccountCredentials for Plaid {} impl ConnectorIntegration< BankAccountCredentials, auth_types::BankAccountCredentialsRequest, auth_types::BankAccountCredentialsResponse, > for Plaid { fn get_headers( &self, req: &auth_types::BankDetailsRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &auth_types::BankDetailsRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/auth/get")) } fn get_request_body( &self, req: &auth_types::BankDetailsRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::BankDetailsRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentAuthBankAccountDetailsType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers( self, req, connectors, )?) .set_body( auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?, ) .build(), )) } fn handle_response( &self, data: &auth_types::BankDetailsRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> { let response: plaid::PlaidBankAccountCredentialsResponse = res .response .parse_struct("PlaidBankAccountCredentialsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; <auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } } impl ConnectorIntegration< RecipientCreate, auth_types::RecipientCreateRequest, auth_types::RecipientCreateResponse, > for Plaid { fn get_headers( &self, req: &auth_types::RecipientCreateRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &auth_types::RecipientCreateRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "/payment_initiation/recipient/create" )) } fn get_request_body( &self, req: &auth_types::RecipientCreateRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::RecipientCreateRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentInitiationRecipientCreateType::get_url( self, req, connectors, )?) .attach_default_headers() .headers( auth_types::PaymentInitiationRecipientCreateType::get_headers( self, req, connectors, )?, ) .set_body( auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?, ) .build(), )) } fn handle_response( &self, data: &auth_types::RecipientCreateRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> { let response: plaid::PlaidRecipientCreateResponse = res .response .parse_struct("PlaidRecipientCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(<auth_types::RecipientCreateRouterData>::from( auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, )) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } }
{ "crate": "pm_auth", "file": "crates/pm_auth/src/connector/plaid.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_pm_auth_4690520216484708083
clm
file
// Repository: hyperswitch // Crate: pm_auth // File: crates/pm_auth/src/connector/plaid/transformers.rs // Contains: 20 structs, 1 enums use std::collections::HashMap; use common_enums::{PaymentMethod, PaymentMethodType}; use common_utils::{id_type, types as util_types}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{core::errors, types}; #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidLinkTokenRequest { client_name: String, country_codes: Vec<String>, language: String, products: Vec<String>, user: User, android_package_name: Option<String>, redirect_uri: Option<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct User { pub client_user_id: id_type::CustomerId, } impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { client_name: item.request.client_name.clone(), country_codes: item.request.country_codes.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "country_codes", }, )?, language: item.request.language.clone().unwrap_or("en".to_string()), products: vec!["auth".to_string()], user: User { client_user_id: item.request.user_info.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "country_codes", }, )?, }, android_package_name: match item.request.client_platform { Some(api_models::enums::ClientPlatform::Android) => { item.request.android_package_name.clone() } Some(api_models::enums::ClientPlatform::Ios) | Some(api_models::enums::ClientPlatform::Web) | Some(api_models::enums::ClientPlatform::Unknown) | None => None, }, redirect_uri: match item.request.client_platform { Some(api_models::enums::ClientPlatform::Ios) => item.request.redirect_uri.clone(), Some(api_models::enums::ClientPlatform::Android) | Some(api_models::enums::ClientPlatform::Web) | Some(api_models::enums::ClientPlatform::Unknown) | None => None, }, }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidLinkTokenResponse { link_token: String, } impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>> for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::LinkTokenResponse { link_token: item.response.link_token, }), ..item.data }) } } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidExchangeTokenRequest { public_token: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidExchangeTokenResponse { pub access_token: String, } impl<F, T> TryFrom< types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>, > for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::ExchangeTokenResponse { access_token: item.response.access_token, }), ..item.data }) } } impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { public_token: item.request.public_token.clone(), }) } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PlaidRecipientCreateRequest { pub name: String, #[serde(flatten)] pub account_data: PlaidRecipientAccountData, pub address: Option<PlaidRecipientCreateAddress>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidRecipientCreateResponse { pub recipient_id: String, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PlaidRecipientAccountData { Iban(Secret<String>), Bacs { sort_code: Secret<String>, account: Secret<String>, }, } impl TryFrom<&types::RecipientAccountData> for PlaidRecipientAccountData { type Error = errors::ConnectorError; fn try_from(item: &types::RecipientAccountData) -> Result<Self, Self::Error> { match item { types::RecipientAccountData::Iban(iban) => Ok(Self::Iban(iban.clone())), types::RecipientAccountData::Bacs { sort_code, account_number, } => Ok(Self::Bacs { sort_code: sort_code.clone(), account: account_number.clone(), }), types::RecipientAccountData::FasterPayments { .. } | types::RecipientAccountData::Sepa(_) | types::RecipientAccountData::SepaInstant(_) | types::RecipientAccountData::Elixir { .. } | types::RecipientAccountData::Bankgiro(_) | types::RecipientAccountData::Plusgiro(_) => { Err(errors::ConnectorError::InvalidConnectorConfig { config: "Invalid payment method selected. Only Iban, Bacs Supported", }) } } } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PlaidRecipientCreateAddress { pub street: String, pub city: String, pub postal_code: String, pub country: String, } impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress { fn from(item: &types::RecipientCreateAddress) -> Self { Self { street: item.street.clone(), city: item.city.clone(), postal_code: item.postal_code.clone(), country: common_enums::CountryAlpha2::to_string(&item.country), } } } impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest { type Error = errors::ConnectorError; fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> { Ok(Self { name: item.request.name.clone(), account_data: PlaidRecipientAccountData::try_from(&item.request.account_data)?, address: item .request .address .as_ref() .map(PlaidRecipientCreateAddress::from), }) } } impl<F, T> From< types::ResponseRouterData< F, PlaidRecipientCreateResponse, T, types::RecipientCreateResponse, >, > for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse> { fn from( item: types::ResponseRouterData< F, PlaidRecipientCreateResponse, T, types::RecipientCreateResponse, >, ) -> Self { Self { response: Ok(types::RecipientCreateResponse { recipient_id: item.response.recipient_id, }), ..item.data } } } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidBankAccountCredentialsRequest { access_token: String, options: Option<BankAccountCredentialsOptions>, } #[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsResponse { pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, pub numbers: PlaidBankAccountCredentialsNumbers, // pub item: PlaidBankAccountCredentialsItem, pub request_id: String, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BankAccountCredentialsOptions { account_ids: Vec<String>, } #[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsAccounts { pub account_id: String, pub name: String, pub subtype: Option<String>, pub balances: Option<PlaidBankAccountCredentialsBalances>, } #[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsBalances { pub available: Option<util_types::FloatMajorUnit>, pub current: Option<util_types::FloatMajorUnit>, pub limit: Option<util_types::FloatMajorUnit>, pub iso_currency_code: Option<String>, pub unofficial_currency_code: Option<String>, pub last_updated_datetime: Option<String>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsNumbers { pub ach: Vec<PlaidBankAccountCredentialsACH>, pub eft: Vec<PlaidBankAccountCredentialsEFT>, pub international: Vec<PlaidBankAccountCredentialsInternational>, pub bacs: Vec<PlaidBankAccountCredentialsBacs>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsItem { pub item_id: String, pub institution_id: Option<String>, pub webhook: Option<String>, pub error: Option<PlaidErrorResponse>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsACH { pub account_id: String, pub account: String, pub routing: String, pub wire_routing: Option<String>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsEFT { pub account_id: String, pub account: String, pub institution: String, pub branch: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsInternational { pub account_id: String, pub iban: String, pub bic: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsBacs { pub account_id: String, pub account: String, pub sort_code: String, } impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> { let options = item.request.optional_ids.as_ref().map(|bank_account_ids| { let ids = bank_account_ids .ids .iter() .map(|id| id.peek().to_string()) .collect::<Vec<_>>(); BankAccountCredentialsOptions { account_ids: ids } }); Ok(Self { access_token: item.request.access_token.peek().to_string(), options, }) } } impl<F, T> TryFrom< types::ResponseRouterData< F, PlaidBankAccountCredentialsResponse, T, types::BankAccountCredentialsResponse, >, > for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< F, PlaidBankAccountCredentialsResponse, T, types::BankAccountCredentialsResponse, >, ) -> Result<Self, Self::Error> { let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts); let mut bank_account_vec = Vec::new(); let mut id_to_subtype = HashMap::new(); accounts_info.into_iter().for_each(|acc| { id_to_subtype.insert( acc.account_id, ( acc.subtype, acc.name, acc.balances.and_then(|balance| balance.available), ), ); }); account_numbers.ach.into_iter().for_each(|ach| { let (acc_type, acc_name, available_balance) = if let Some(( _type, name, available_balance, )) = id_to_subtype.get(&ach.account_id) { (_type.to_owned(), Some(name.clone()), *available_balance) } else { (None, None, None) }; let account_details = types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch { account_number: Secret::new(ach.account), routing_number: Secret::new(ach.routing), }); let bank_details_new = types::BankAccountDetails { account_name: acc_name, account_details, payment_method_type: PaymentMethodType::Ach, payment_method: PaymentMethod::BankDebit, account_id: ach.account_id.into(), account_type: acc_type, balance: available_balance, }; bank_account_vec.push(bank_details_new); }); account_numbers.bacs.into_iter().for_each(|bacs| { let (acc_type, acc_name, available_balance) = if let Some((_type, name, available_balance)) = id_to_subtype.get(&bacs.account_id) { (_type.to_owned(), Some(name.clone()), *available_balance) } else { (None, None, None) }; let account_details = types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs { account_number: Secret::new(bacs.account), sort_code: Secret::new(bacs.sort_code), }); let bank_details_new = types::BankAccountDetails { account_name: acc_name, account_details, payment_method_type: PaymentMethodType::Bacs, payment_method: PaymentMethod::BankDebit, account_id: bacs.account_id.into(), account_type: acc_type, balance: available_balance, }; bank_account_vec.push(bank_details_new); }); account_numbers.international.into_iter().for_each(|sepa| { let (acc_type, acc_name, available_balance) = if let Some((_type, name, available_balance)) = id_to_subtype.get(&sepa.account_id) { (_type.to_owned(), Some(name.clone()), *available_balance) } else { (None, None, None) }; let account_details = types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa { iban: Secret::new(sepa.iban), bic: Secret::new(sepa.bic), }); let bank_details_new = types::BankAccountDetails { account_name: acc_name, account_details, payment_method_type: PaymentMethodType::Sepa, payment_method: PaymentMethod::BankDebit, account_id: sepa.account_id.into(), account_type: acc_type, balance: available_balance, }; bank_account_vec.push(bank_details_new); }); Ok(Self { response: Ok(types::BankAccountCredentialsResponse { credentials: bank_account_vec, }), ..item.data }) } } pub struct PlaidAuthType { pub client_id: Secret<String>, pub secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self { client_id: client_id.to_owned(), secret: secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct PlaidErrorResponse { pub display_message: Option<String>, pub error_code: Option<String>, pub error_message: String, pub error_type: Option<String>, }
{ "crate": "pm_auth", "file": "crates/pm_auth/src/connector/plaid/transformers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 20, "num_tables": null, "score": null, "total_crates": null }
file_kgraph_utils_5670644676026337867
clm
file
// Repository: hyperswitch // Crate: kgraph_utils // File: crates/kgraph_utils/src/types.rs // Contains: 4 structs, 1 enums use std::collections::{HashMap, HashSet}; use api_models::enums as api_enums; use serde::Deserialize; #[derive(Debug, Deserialize, Clone, Default)] pub struct CountryCurrencyFilter { pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>, pub default_configs: Option<PaymentMethodFilters>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] pub enum PaymentMethodFilterKey { PaymentMethodType(api_enums::PaymentMethodType), CardNetwork(api_enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { pub currency: Option<HashSet<api_enums::Currency>>, pub country: Option<HashSet<api_enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { pub capture_method: Option<api_enums::CaptureMethod>, }
{ "crate": "kgraph_utils", "file": "crates/kgraph_utils/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-1657644917476141434
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/crm.rs // Contains: 2 structs, 1 enums 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 reqwest; 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 } }
{ "crate": "external_services", "file": "crates/external_services/src/crm.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-6715067086724757001
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/grpc_client.rs // Contains: 5 structs, 0 enums /// 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 serde_urlencoded; #[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, /// 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>, request_id: Option<String>, shadow_mode: Option<bool>, } /// Type aliase for GrpcHeaders builder in initial stage pub type GrpcHeadersUcsBuilderInitial = GrpcHeadersUcsBuilder<((String,), (), (), (), (Option<String>,), (Option<bool>,))>; /// Type aliase for GrpcHeaders builder in intermediate stage pub type GrpcHeadersUcsBuilderFinal = GrpcHeadersUcsBuilder<( (String,), (LineageIds,), (Option<String>,), (Option<ucs_types::UcsReferenceId>,), (Option<String>,), (Option<bool>,), )>; /// struct to represent set of Lineage ids #[derive(Debug, 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 }
{ "crate": "external_services", "file": "crates/external_services/src/grpc_client.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-266437963637241771
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/email.rs // Contains: 3 structs, 2 enums //! 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, }
{ "crate": "external_services", "file": "crates/external_services/src/email.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-8378288315682306120
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/file_storage.rs // Contains: 1 structs, 2 enums //! 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, }
{ "crate": "external_services", "file": "crates/external_services/src/file_storage.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-1870006260615333179
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/hubspot_proxy.rs // Contains: 1 structs, 0 enums 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() } } }
{ "crate": "external_services", "file": "crates/external_services/src/hubspot_proxy.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-3341768810910976036
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/hashicorp_vault/core.rs // Contains: 1 structs, 2 enums //! 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, }
{ "crate": "external_services", "file": "crates/external_services/src/hashicorp_vault/core.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-922726820123796563
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/file_storage/file_system.rs // Contains: 1 structs, 1 enums //! 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, }
{ "crate": "external_services", "file": "crates/external_services/src/file_storage/file_system.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_7892945919252199756
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/file_storage/aws_s3.rs // Contains: 2 structs, 1 enums 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), }
{ "crate": "external_services", "file": "crates/external_services/src/file_storage/aws_s3.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_external_services_2447505922293363475
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/no_encryption/core.rs // Contains: 1 structs, 0 enums //! 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() } }
{ "crate": "external_services", "file": "crates/external_services/src/no_encryption/core.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-496491792896730278
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/aws_kms/core.rs // Contains: 2 structs, 1 enums //! 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: 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: 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 decrypt_output = self .inner_client .decrypt() .key_id(&self.key_id) .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 encrypted_output = self .inner_client .encrypt() .key_id(&self.key_id) .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, } 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.key_id.is_default_or_empty(), || { Err("KMS AWS key ID must not be empty") })?; when(self.region.is_default_or_empty(), || { Err("KMS AWS region must not be empty") }) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::print_stdout)] #[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: "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: "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}"); } }
{ "crate": "external_services", "file": "crates/external_services/src/aws_kms/core.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_external_services_6443451087665229257
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/superposition/types.rs // Contains: 3 structs, 1 enums //! 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 })) } }
{ "crate": "external_services", "file": "crates/external_services/src/superposition/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_external_services_6409812584319567701
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/grpc_client/health_check_client.rs // Contains: 1 structs, 1 enums 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) } }
{ "crate": "external_services", "file": "crates/external_services/src/grpc_client/health_check_client.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-4456388263178254287
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/grpc_client/unified_connector_service.rs // Contains: 4 structs, 1 enums 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, PaymentServiceAuthorizeResponse, PaymentServiceTransformRequest, PaymentServiceTransformResponse, }; 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>, } /// 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 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 connect_result = timeout( Duration::from_secs(unified_connector_service_client_config.connection_timeout), PaymentServiceClient::connect(uri), ) .await; match connect_result { Ok(Ok(client)) => { logger::info!("Successfully connected to Unified Connector Service"); Some(Self { client }) } Ok(Err(err)) => { logger::error!(error = ?err, "Failed to connect to Unified Connector Service"); None } 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 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 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 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" ) }) } /// 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" ) }) } } /// 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(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, parse( consts::UCS_HEADER_REFERENCE_ID, reference_id.get_string_repr(), )?, ); }; if let Some(request_id) = grpc_headers.request_id { metadata.append( common_utils_consts::X_REQUEST_ID, parse(common_utils_consts::X_REQUEST_ID, &request_id)?, ); }; if let Some(shadow_mode) = grpc_headers.shadow_mode { metadata.append( common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE, parse( common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE, &shadow_mode.to_string(), )?, ); } if let Err(err) = grpc_headers .tenant_id .parse() .map(|tenant_id| metadata.append(common_utils_consts::TENANT_HEADER, tenant_id)) { logger::error!( header_parse_error=?err, tenant_id=?grpc_headers.tenant_id, "Failed to parse tenant_id header for UCS gRPC request: {}", common_utils_consts::TENANT_HEADER ); } Ok(metadata) }
{ "crate": "external_services", "file": "crates/external_services/src/grpc_client/unified_connector_service.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_external_services_1877815401306676267
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/grpc_client/dynamic_routing.rs // Contains: 1 structs, 2 enums /// Module for Contract based routing pub mod contract_routing_client; use std::fmt::Debug; use common_utils::errors::CustomResult; use router_env::logger; use serde; /// 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), } } }
{ "crate": "external_services", "file": "crates/external_services/src/grpc_client/dynamic_routing.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_8130465968237760008
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/grpc_client/revenue_recovery.rs // Contains: 1 structs, 0 enums /// 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 }
{ "crate": "external_services", "file": "crates/external_services/src/grpc_client/revenue_recovery.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-8283357843249390002
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs // Contains: 1 structs, 1 enums 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) } }
{ "crate": "external_services", "file": "crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_5482816843224657302
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/email/ses.rs // Contains: 2 structs, 1 enums 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(()) } }
{ "crate": "external_services", "file": "crates/external_services/src/email/ses.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_external_services_1245573268226924603
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/email/no_email.rs // Contains: 1 structs, 0 enums 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(()) } }
{ "crate": "external_services", "file": "crates/external_services/src/email/no_email.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_external_services_-4192699438808080161
clm
file
// Repository: hyperswitch // Crate: external_services // File: crates/external_services/src/email/smtp.rs // Contains: 2 structs, 2 enums 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), }
{ "crate": "external_services", "file": "crates/external_services/src/email/smtp.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_euclid_macros_2214265624194018656
clm
file
// Repository: hyperswitch // Crate: euclid_macros // File: crates/euclid_macros/src/inner/knowledge.rs // Contains: 2 structs, 4 enums use std::{ fmt::{Display, Formatter}, hash::Hash, rc::Rc, }; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use rustc_hash::{FxHashMap, FxHashSet}; use syn::{parse::Parse, Token}; mod strength { syn::custom_punctuation!(Normal, ->); syn::custom_punctuation!(Strong, ->>); } mod kw { syn::custom_keyword!(any); syn::custom_keyword!(not); } #[derive(Clone, PartialEq, Eq, Hash)] enum Comparison { LessThan, Equal, GreaterThan, GreaterThanEqual, LessThanEqual, } impl Display for Comparison { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let symbol = match self { Self::LessThan => "< ", Self::Equal => return Ok(()), Self::GreaterThanEqual => ">= ", Self::LessThanEqual => "<= ", Self::GreaterThan => "> ", }; write!(f, "{symbol}") } } impl Parse for Comparison { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { if input.peek(Token![>]) { input.parse::<Token![>]>()?; Ok(Self::GreaterThan) } else if input.peek(Token![<]) { input.parse::<Token![<]>()?; Ok(Self::LessThan) } else if input.peek(Token!(<=)) { input.parse::<Token![<=]>()?; Ok(Self::LessThanEqual) } else if input.peek(Token!(>=)) { input.parse::<Token![>=]>()?; Ok(Self::GreaterThanEqual) } else { Ok(Self::Equal) } } } #[derive(Clone, PartialEq, Eq, Hash)] enum ValueType { Any, EnumVariant(String), Number { number: i64, comparison: Comparison }, } impl ValueType { fn to_string(&self, key: &str) -> String { match self { Self::Any => format!("{key}(any)"), Self::EnumVariant(s) => format!("{key}({s})"), Self::Number { number, comparison } => { format!("{key}({comparison}{number})") } } } } impl Parse for ValueType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(syn::Ident) { let ident: syn::Ident = input.parse()?; Ok(Self::EnumVariant(ident.to_string())) } else if lookahead.peek(Token![>]) || lookahead.peek(Token![<]) || lookahead.peek(syn::LitInt) { let comparison: Comparison = input.parse()?; let number: syn::LitInt = input.parse()?; let num_val = number.base10_parse::<i64>()?; Ok(Self::Number { number: num_val, comparison, }) } else { Err(lookahead.error()) } } } #[derive(Clone, PartialEq, Eq, Hash)] struct Atom { key: String, value: ValueType, } impl Display for Atom { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.value.to_string(&self.key)) } } impl Parse for Atom { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let maybe_any: syn::Ident = input.parse()?; if maybe_any == "any" { let actual_key: syn::Ident = input.parse()?; Ok(Self { key: actual_key.to_string(), value: ValueType::Any, }) } else { let content; syn::parenthesized!(content in input); let value: ValueType = content.parse()?; Ok(Self { key: maybe_any.to_string(), value, }) } } } #[derive(Clone, PartialEq, Eq, Hash, strum::Display)] enum Strength { Normal, Strong, } impl Parse for Strength { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(strength::Strong) { input.parse::<strength::Strong>()?; Ok(Self::Strong) } else if lookahead.peek(strength::Normal) { input.parse::<strength::Normal>()?; Ok(Self::Normal) } else { Err(lookahead.error()) } } } #[derive(Clone, PartialEq, Eq, Hash, strum::Display)] enum Relation { Positive, Negative, } enum AtomType { Value { relation: Relation, atom: Rc<Atom>, }, InAggregator { key: String, values: Vec<String>, relation: Relation, }, } fn parse_atom_type_inner( input: syn::parse::ParseStream<'_>, key: syn::Ident, relation: Relation, ) -> syn::Result<AtomType> { let result = if input.peek(Token![in]) { input.parse::<Token![in]>()?; let bracketed; syn::bracketed!(bracketed in input); let mut values = Vec::<String>::new(); let first: syn::Ident = bracketed.parse()?; values.push(first.to_string()); while !bracketed.is_empty() { bracketed.parse::<Token![,]>()?; let next: syn::Ident = bracketed.parse()?; values.push(next.to_string()); } AtomType::InAggregator { key: key.to_string(), values, relation, } } else if input.peek(kw::any) { input.parse::<kw::any>()?; AtomType::Value { relation, atom: Rc::new(Atom { key: key.to_string(), value: ValueType::Any, }), } } else { let value: ValueType = input.parse()?; AtomType::Value { relation, atom: Rc::new(Atom { key: key.to_string(), value, }), } }; Ok(result) } impl Parse for AtomType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let key: syn::Ident = input.parse()?; let content; syn::parenthesized!(content in input); let relation = if content.peek(kw::not) { content.parse::<kw::not>()?; Relation::Negative } else { Relation::Positive }; let result = parse_atom_type_inner(&content, key, relation)?; if !content.is_empty() { Err(content.error("Unexpected input received after atom value")) } else { Ok(result) } } } fn parse_rhs_atom(input: syn::parse::ParseStream<'_>) -> syn::Result<Atom> { let key: syn::Ident = input.parse()?; let content; syn::parenthesized!(content in input); let lookahead = content.lookahead1(); let value_type = if lookahead.peek(kw::any) { content.parse::<kw::any>()?; ValueType::Any } else if lookahead.peek(syn::Ident) { let variant = content.parse::<syn::Ident>()?; ValueType::EnumVariant(variant.to_string()) } else { return Err(lookahead.error()); }; if !content.is_empty() { Err(content.error("Unexpected input received after atom value")) } else { Ok(Atom { key: key.to_string(), value: value_type, }) } } struct Rule { lhs: Vec<AtomType>, strength: Strength, rhs: Rc<Atom>, } impl Parse for Rule { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let first_atom: AtomType = input.parse()?; let mut lhs: Vec<AtomType> = vec![first_atom]; while input.peek(Token![&]) { input.parse::<Token![&]>()?; let and_atom: AtomType = input.parse()?; lhs.push(and_atom); } let strength: Strength = input.parse()?; let rhs: Rc<Atom> = Rc::new(parse_rhs_atom(input)?); input.parse::<Token![;]>()?; Ok(Self { lhs, strength, rhs }) } } #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, } impl Parse for Program { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let mut rules: Vec<Rc<Rule>> = Vec::new(); while !input.is_empty() { rules.push(Rc::new(input.parse::<Rule>()?)); } Ok(Self { rules }) } } struct GenContext { next_idx: usize, next_node_idx: usize, idx2atom: FxHashMap<usize, Rc<Atom>>, atom2idx: FxHashMap<Rc<Atom>, usize>, edges: FxHashMap<usize, FxHashSet<usize>>, compiled_atoms: FxHashMap<Rc<Atom>, proc_macro2::Ident>, } impl GenContext { fn new() -> Self { Self { next_idx: 1, next_node_idx: 1, idx2atom: FxHashMap::default(), atom2idx: FxHashMap::default(), edges: FxHashMap::default(), compiled_atoms: FxHashMap::default(), } } fn register_node(&mut self, atom: Rc<Atom>) -> usize { if let Some(idx) = self.atom2idx.get(&atom) { *idx } else { let this_idx = self.next_idx; self.next_idx += 1; self.idx2atom.insert(this_idx, Rc::clone(&atom)); self.atom2idx.insert(atom, this_idx); this_idx } } fn register_edge(&mut self, from: usize, to: usize) -> Result<(), String> { let node_children = self.edges.entry(from).or_default(); if node_children.contains(&to) { Err("Duplicate edge detected".to_string()) } else { node_children.insert(to); self.edges.entry(to).or_default(); Ok(()) } } fn register_rule(&mut self, rule: &Rule) -> Result<(), String> { let to_idx = self.register_node(Rc::clone(&rule.rhs)); for atom_type in &rule.lhs { if let AtomType::Value { atom, .. } = atom_type { let from_idx = self.register_node(Rc::clone(atom)); self.register_edge(from_idx, to_idx)?; } } Ok(()) } fn cycle_dfs( &self, node_id: usize, explored: &mut FxHashSet<usize>, visited: &mut FxHashSet<usize>, order: &mut Vec<usize>, ) -> Result<Option<Vec<usize>>, String> { if explored.contains(&node_id) { let position = order .iter() .position(|v| *v == node_id) .ok_or_else(|| "Error deciding cycle order".to_string())?; let cycle_order = order .get(position..) .ok_or_else(|| "Error getting cycle order".to_string())? .to_vec(); Ok(Some(cycle_order)) } else if visited.contains(&node_id) { Ok(None) } else { visited.insert(node_id); explored.insert(node_id); order.push(node_id); let dests = self .edges .get(&node_id) .ok_or_else(|| "Error getting edges of node".to_string())?; for dest in dests.iter().copied() { if let Some(cycle) = self.cycle_dfs(dest, explored, visited, order)? { return Ok(Some(cycle)); } } order.pop(); Ok(None) } } fn detect_graph_cycles(&self) -> Result<(), String> { let start_nodes = self.edges.keys().copied().collect::<Vec<usize>>(); let mut total_visited = FxHashSet::<usize>::default(); for node_id in start_nodes.iter().copied() { let mut explored = FxHashSet::<usize>::default(); let mut order = Vec::<usize>::new(); match self.cycle_dfs(node_id, &mut explored, &mut total_visited, &mut order)? { None => {} Some(order) => { let mut display_strings = Vec::<String>::with_capacity(order.len() + 1); for cycle_node_id in order { let node = self.idx2atom.get(&cycle_node_id).ok_or_else(|| { "Failed to find node during cycle display creation".to_string() })?; display_strings.push(node.to_string()); } let first = display_strings .first() .cloned() .ok_or("Unable to fill cycle display array")?; display_strings.push(first); return Err(format!("Found cycle: {}", display_strings.join(" -> "))); } } } Ok(()) } fn next_node_ident(&mut self) -> (proc_macro2::Ident, usize) { let this_idx = self.next_node_idx; self.next_node_idx += 1; (format_ident!("_node_{this_idx}"), this_idx) } fn compile_atom( &mut self, atom: &Rc<Atom>, tokens: &mut TokenStream, ) -> Result<proc_macro2::Ident, String> { let maybe_ident = self.compiled_atoms.get(atom); if let Some(ident) = maybe_ident { Ok(ident.clone()) } else { let (identifier, _) = self.next_node_ident(); let key = format_ident!("{}", &atom.key); let the_value = match &atom.value { ValueType::Any => quote! { cgraph::NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) }, ValueType::EnumVariant(variant) => { let variant = format_ident!("{}", variant); quote! { cgraph::NodeValue::Value(DirValue::#key(#key::#variant)) } } ValueType::Number { number, comparison } => { let comp_type = match comparison { Comparison::Equal => quote! { None }, Comparison::LessThan => quote! { Some(NumValueRefinement::LessThan) }, Comparison::GreaterThan => quote! { Some(NumValueRefinement::GreaterThan) }, Comparison::GreaterThanEqual => quote! { Some(NumValueRefinement::GreaterThanEqual) }, Comparison::LessThanEqual => quote! { Some(NumValueRefinement::LessThanEqual) }, }; quote! { cgraph::NodeValue::Value(DirValue::#key(NumValue { number: #number, refinement: #comp_type, })) } } }; let compiled = quote! { let #identifier = graph.make_value_node(#the_value, None, None::<()>); }; tokens.extend(compiled); self.compiled_atoms .insert(Rc::clone(atom), identifier.clone()); Ok(identifier) } } fn compile_atom_type( &mut self, atom_type: &AtomType, tokens: &mut TokenStream, ) -> Result<(proc_macro2::Ident, Relation), String> { match atom_type { AtomType::Value { relation, atom } => { let node_ident = self.compile_atom(atom, tokens)?; Ok((node_ident, relation.clone())) } AtomType::InAggregator { key, values, relation, } => { let key_ident = format_ident!("{key}"); let mut values_tokens: Vec<TokenStream> = Vec::new(); for value in values { let value_ident = format_ident!("{value}"); values_tokens.push(quote! { DirValue::#key_ident(#key_ident::#value_ident) }); } let (node_ident, _) = self.next_node_ident(); let node_code = quote! { let #node_ident = graph.make_in_aggregator( Vec::from_iter([#(#values_tokens),*]), None, None::<()>, ).expect("Failed to make In aggregator"); }; tokens.extend(node_code); Ok((node_ident, relation.clone())) } } } fn compile_rule(&mut self, rule: &Rule, tokens: &mut TokenStream) -> Result<(), String> { let rhs_ident = self.compile_atom(&rule.rhs, tokens)?; let mut node_details: Vec<(proc_macro2::Ident, Relation)> = Vec::with_capacity(rule.lhs.len()); for lhs_atom_type in &rule.lhs { let details = self.compile_atom_type(lhs_atom_type, tokens)?; node_details.push(details); } if node_details.len() <= 1 { let strength = format_ident!("{}", rule.strength.to_string()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); tokens.extend(quote! { graph.make_edge(#from_node, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::#relation, None::<cgraph::DomainId>) .expect("Failed to make edge"); }); } } else { let mut all_agg_nodes: Vec<TokenStream> = Vec::with_capacity(node_details.len()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); all_agg_nodes.push( quote! { (#from_node, cgraph::Relation::#relation, cgraph::Strength::Strong) }, ); } let strength = format_ident!("{}", rule.strength.to_string()); let (agg_node_ident, _) = self.next_node_ident(); tokens.extend(quote! { let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, None) .expect("Failed to make all aggregator node"); graph.make_edge(#agg_node_ident, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::Positive, None::<cgraph::DomainId>) .expect("Failed to create all aggregator edge"); }); } Ok(()) } fn compile(&mut self, program: Program) -> Result<TokenStream, String> { let mut tokens = TokenStream::new(); for rule in &program.rules { self.compile_rule(rule, &mut tokens)?; } let compiled = quote! {{ use euclid_graph_prelude::*; let mut graph = cgraph::ConstraintGraphBuilder::new(); #tokens graph.build() }}; Ok(compiled) } } pub(crate) fn knowledge_inner(ts: TokenStream) -> syn::Result<TokenStream> { let program = syn::parse::<Program>(ts.into())?; let mut gen_context = GenContext::new(); for rule in &program.rules { gen_context .register_rule(rule) .map_err(|msg| syn::Error::new(Span::call_site(), msg))?; } gen_context .detect_graph_cycles() .map_err(|msg| syn::Error::new(Span::call_site(), msg))?; gen_context .compile(program) .map_err(|msg| syn::Error::new(Span::call_site(), msg)) }
{ "crate": "euclid_macros", "file": "crates/euclid_macros/src/inner/knowledge.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_masking_5247745843885998422
clm
file
// Repository: hyperswitch // Crate: masking // File: crates/masking/tests/basic.rs // Contains: 5 structs, 0 enums #![allow(dead_code, clippy::unwrap_used, clippy::panic_in_result_fn)] use masking::Secret; #[cfg(feature = "serde")] use masking::SerializableSecret; #[cfg(feature = "alloc")] use masking::ZeroizableSecret; #[cfg(feature = "serde")] use serde::Serialize; #[test] fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { #[cfg_attr(feature = "serde", derive(Serialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct AccountNumber(String); #[cfg(feature = "alloc")] impl ZeroizableSecret for AccountNumber { fn zeroize(&mut self) { self.0.zeroize(); } } #[cfg(feature = "serde")] impl SerializableSecret for AccountNumber {} #[cfg_attr(feature = "serde", derive(Serialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct Composite { secret_number: Secret<AccountNumber>, not_secret: String, } // construct let secret_number = Secret::<AccountNumber>::new(AccountNumber("abc".to_string())); let not_secret = "not secret".to_string(); let composite = Composite { secret_number, not_secret, }; // clone #[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal let composite2 = composite.clone(); assert_eq!(composite, composite2); // format let got = format!("{composite:?}"); let exp = r#"Composite { secret_number: *** basic::basic::AccountNumber ***, not_secret: "not secret" }"#; assert_eq!(got, exp); // serialize #[cfg(feature = "serde")] { let got = serde_json::to_string(&composite).unwrap(); let exp = r#"{"secret_number":"abc","not_secret":"not secret"}"#; assert_eq!(got, exp); } // end Ok(()) } #[test] fn without_serialize() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { #[cfg_attr(feature = "serde", derive(Serialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct AccountNumber(String); #[cfg(feature = "alloc")] impl ZeroizableSecret for AccountNumber { fn zeroize(&mut self) { self.0.zeroize(); } } #[cfg_attr(feature = "serde", derive(Serialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct Composite { #[cfg_attr(feature = "serde", serde(skip))] secret_number: Secret<AccountNumber>, not_secret: String, } // construct let secret_number = Secret::<AccountNumber>::new(AccountNumber("abc".to_string())); let not_secret = "not secret".to_string(); let composite = Composite { secret_number, not_secret, }; // format let got = format!("{composite:?}"); let exp = r#"Composite { secret_number: *** basic::without_serialize::AccountNumber ***, not_secret: "not secret" }"#; assert_eq!(got, exp); // serialize #[cfg(feature = "serde")] { let got = serde_json::to_string(&composite).unwrap(); let exp = r#"{"not_secret":"not secret"}"#; assert_eq!(got, exp); } // end Ok(()) } #[test] fn for_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { #[cfg_attr(all(feature = "alloc", feature = "serde"), derive(Serialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct Composite { secret_number: Secret<String>, not_secret: String, } // construct let secret_number = Secret::<String>::new("abc".to_string()); let not_secret = "not secret".to_string(); let composite = Composite { secret_number, not_secret, }; // clone #[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal let composite2 = composite.clone(); assert_eq!(composite, composite2); // format let got = format!("{composite:?}"); let exp = r#"Composite { secret_number: *** alloc::string::String ***, not_secret: "not secret" }"#; assert_eq!(got, exp); // serialize #[cfg(all(feature = "alloc", feature = "serde"))] { let got = serde_json::to_string(&composite).unwrap(); let exp = r#"{"secret_number":"abc","not_secret":"not secret"}"#; assert_eq!(got, exp); } // end Ok(()) }
{ "crate": "masking", "file": "crates/masking/tests/basic.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_masking_8858197806504010837
clm
file
// Repository: hyperswitch // Crate: masking // File: crates/masking/src/bytes.rs // Contains: 1 structs, 0 enums //! Optional `Secret` wrapper type for the `bytes::BytesMut` crate. use core::fmt; use bytes::BytesMut; #[cfg(all(feature = "bytes", feature = "serde"))] use serde::de::{self, Deserialize}; use super::{PeekInterface, ZeroizableSecret}; /// Instance of [`BytesMut`] protected by a type that impls the [`ExposeInterface`] /// trait like `Secret<T>`. /// /// Because of the nature of how the `BytesMut` type works, it needs some special /// care in order to have a proper zeroizing drop handler. #[derive(Clone)] #[cfg_attr(docsrs, cfg(feature = "bytes"))] pub struct SecretBytesMut(BytesMut); impl SecretBytesMut { /// Wrap bytes in `SecretBytesMut` pub fn new(bytes: impl Into<BytesMut>) -> Self { Self(bytes.into()) } } impl PeekInterface<BytesMut> for SecretBytesMut { fn peek(&self) -> &BytesMut { &self.0 } fn peek_mut(&mut self) -> &mut BytesMut { &mut self.0 } } impl fmt::Debug for SecretBytesMut { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SecretBytesMut([REDACTED])") } } impl From<BytesMut> for SecretBytesMut { fn from(bytes: BytesMut) -> Self { Self::new(bytes) } } impl Drop for SecretBytesMut { fn drop(&mut self) { self.0.resize(self.0.capacity(), 0); self.0.as_mut().zeroize(); debug_assert!(self.0.as_ref().iter().all(|b| *b == 0)); } } #[cfg(all(feature = "bytes", feature = "serde"))] impl<'de> Deserialize<'de> for SecretBytesMut { fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct SecretBytesVisitor; impl<'de> de::Visitor<'de> for SecretBytesVisitor { type Value = SecretBytesMut; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("byte array") } #[inline] fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: de::Error, { let mut bytes = BytesMut::with_capacity(v.len()); bytes.extend_from_slice(v); Ok(SecretBytesMut(bytes)) } #[inline] fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> where V: de::SeqAccess<'de>, { // 4096 is cargo culted from upstream let len = core::cmp::min(seq.size_hint().unwrap_or(0), 4096); let mut bytes = BytesMut::with_capacity(len); use bytes::BufMut; while let Some(value) = seq.next_element()? { bytes.put_u8(value); } Ok(SecretBytesMut(bytes)) } } deserializer.deserialize_bytes(SecretBytesVisitor) } }
{ "crate": "masking", "file": "crates/masking/src/bytes.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_injector_-5471578230891535080
clm
file
// Repository: hyperswitch // Crate: injector // File: crates/injector/src/injector.rs // Contains: 2 structs, 1 enums pub mod core { use std::collections::HashMap; use async_trait::async_trait; use common_utils::request::{Method, RequestBuilder, RequestContent}; use error_stack::{self, ResultExt}; use masking::{self, ExposeInterface}; use nom::{ bytes::complete::{tag, take_while1}, character::complete::{char, multispace0}, sequence::{delimited, preceded, terminated}, IResult, }; use router_env::{instrument, logger, tracing}; use serde_json::Value; use thiserror::Error; use crate as injector_types; use crate::{ types::{ContentType, InjectorRequest, InjectorResponse, IntoInjectorResponse}, vault_metadata::VaultMetadataExtractorExt, }; impl From<injector_types::HttpMethod> for Method { fn from(method: injector_types::HttpMethod) -> Self { match method { injector_types::HttpMethod::GET => Self::Get, injector_types::HttpMethod::POST => Self::Post, injector_types::HttpMethod::PUT => Self::Put, injector_types::HttpMethod::PATCH => Self::Patch, injector_types::HttpMethod::DELETE => Self::Delete, } } } /// Proxy configuration structure (copied from hyperswitch_interfaces to make injector standalone) #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct Proxy { /// The URL of the HTTP proxy server. pub http_url: Option<String>, /// The URL of the HTTPS proxy server. pub https_url: Option<String>, /// The timeout duration (in seconds) for idle connections in the proxy pool. pub idle_pool_connection_timeout: Option<u64>, /// A comma-separated list of hosts that should bypass the proxy. pub bypass_proxy_hosts: Option<String>, } impl Default for Proxy { fn default() -> Self { Self { http_url: Default::default(), https_url: Default::default(), idle_pool_connection_timeout: Some(90), bypass_proxy_hosts: Default::default(), } } } /// Create HTTP client using the proven external_services create_client logic 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>>, ) -> error_stack::Result<reqwest::Client, InjectorError> { logger::debug!( has_client_cert = client_certificate.is_some(), has_client_key = client_certificate_key.is_some(), has_ca_cert = ca_certificate.is_some(), "Creating HTTP client" ); // 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."); } let client_builder = get_client_builder(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(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!( "Failed to construct client with certificate and certificate key: {:?}", e ); }); } // Case 2: Use provided CA certificate for server authentication only (one-way TLS) if let Some(ca_pem) = 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(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!("Failed to parse CA certificate PEM block: {:?}", e) })?; let client_builder = get_client_builder(proxy_config)?.add_root_certificate(cert); return client_builder .use_rustls_tls() .build() .change_context(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!("Failed to construct client with CA certificate: {:?}", e); }); } // Case 3: Default client (no certs) get_base_client(proxy_config) } /// Helper functions from external_services fn get_client_builder( proxy_config: &Proxy, ) -> error_stack::Result<reqwest::ClientBuilder, InjectorError> { let mut client_builder = reqwest::Client::builder(); // Configure proxy if provided if let Some(proxy_url) = &proxy_config.https_url { let proxy = reqwest::Proxy::https(proxy_url) .change_context(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!("Failed to configure HTTPS proxy: {:?}", e); })?; client_builder = client_builder.proxy(proxy); } if let Some(proxy_url) = &proxy_config.http_url { let proxy = reqwest::Proxy::http(proxy_url) .change_context(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!("Failed to configure HTTP proxy: {:?}", e); })?; client_builder = client_builder.proxy(proxy); } Ok(client_builder) } fn get_base_client( proxy_config: &Proxy, ) -> error_stack::Result<reqwest::Client, InjectorError> { let client_builder = get_client_builder(proxy_config)?; client_builder .build() .change_context(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!("Failed to build default HTTP client: {:?}", e); }) } fn create_identity_from_certificate_and_key( encoded_certificate: masking::Secret<String>, encoded_certificate_key: masking::Secret<String>, ) -> error_stack::Result<reqwest::Identity, InjectorError> { let cert_str = encoded_certificate.expose(); let key_str = encoded_certificate_key.expose(); let combined_pem = format!("{cert_str}\n{key_str}"); reqwest::Identity::from_pem(combined_pem.as_bytes()) .change_context(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!( "Failed to create identity from certificate and key: {:?}", e ); }) } fn create_certificate( encoded_certificate: masking::Secret<String>, ) -> error_stack::Result<Vec<reqwest::Certificate>, InjectorError> { let cert_str = encoded_certificate.expose(); let cert = reqwest::Certificate::from_pem(cert_str.as_bytes()) .change_context(InjectorError::HttpRequestFailed) .inspect_err(|e| { logger::error!("Failed to create certificate from PEM: {:?}", e); })?; Ok(vec![cert]) } /// Generic function to log HTTP request errors with detailed error type information fn log_and_convert_http_error(e: reqwest::Error, context: &str) -> InjectorError { let error_msg = e.to_string(); logger::error!("HTTP request failed in {}: {}", context, error_msg); // Log specific error types for debugging if e.is_timeout() { logger::error!("Request timed out in {}", context); } if e.is_connect() { logger::error!("Connection error occurred in {}", context); } if e.is_request() { logger::error!("Request construction error in {}", context); } if e.is_decode() { logger::error!("Response decoding error in {}", context); } InjectorError::HttpRequestFailed } /// Apply certificate configuration to request builder and return built request fn build_request_with_certificates( mut request_builder: RequestBuilder, config: &injector_types::ConnectionConfig, ) -> common_utils::request::Request { // Add certificate configuration if provided if let Some(cert_content) = &config.client_cert { request_builder = request_builder.add_certificate(Some(cert_content.clone())); } if let Some(key_content) = &config.client_key { request_builder = request_builder.add_certificate_key(Some(key_content.clone())); } if let Some(ca_content) = &config.ca_cert { request_builder = request_builder.add_ca_certificate_pem(Some(ca_content.clone())); } request_builder.build() } /// Simplified HTTP client for injector using the proven external_services create_client logic #[instrument(skip_all)] pub async fn send_request( client_proxy: &Proxy, request: common_utils::request::Request, _option_timeout_secs: Option<u64>, ) -> error_stack::Result<reqwest::Response, InjectorError> { logger::info!( has_client_cert = request.certificate.is_some(), has_client_key = request.certificate_key.is_some(), has_ca_cert = request.ca_certificate.is_some(), "Making HTTP request using standalone injector HTTP client with configuration" ); // Create reqwest client using the proven create_client function let client = create_client( client_proxy, request.certificate.clone(), request.certificate_key.clone(), request.ca_certificate.clone(), )?; // Build the request let method = match request.method { Method::Get => reqwest::Method::GET, Method::Post => reqwest::Method::POST, Method::Put => reqwest::Method::PUT, Method::Patch => reqwest::Method::PATCH, Method::Delete => reqwest::Method::DELETE, }; let mut req_builder = client.request(method, &request.url); // Add headers for (key, value) in &request.headers { let header_value = match value { masking::Maskable::Masked(secret) => secret.clone().expose(), masking::Maskable::Normal(normal) => normal.clone(), }; req_builder = req_builder.header(key, header_value); } // Add body if present if let Some(body) = request.body { match body { RequestContent::Json(payload) => { req_builder = req_builder.json(&payload); } RequestContent::FormUrlEncoded(payload) => { req_builder = req_builder.form(&payload); } RequestContent::RawBytes(payload) => { req_builder = req_builder.body(payload); } _ => { logger::warn!("Unsupported request content type, using raw bytes"); } } } // Send the request let response = req_builder .send() .await .map_err(|e| log_and_convert_http_error(e, "send_request"))?; logger::info!( status_code = response.status().as_u16(), "HTTP request completed successfully" ); Ok(response) } #[derive(Error, Debug)] pub enum InjectorError { #[error("Token replacement failed: {0}")] TokenReplacementFailed(String), #[error("HTTP request failed")] HttpRequestFailed, #[error("Serialization error: {0}")] SerializationError(String), #[error("Invalid template: {0}")] InvalidTemplate(String), } #[instrument(skip_all)] pub async fn injector_core( request: InjectorRequest, ) -> error_stack::Result<InjectorResponse, InjectorError> { logger::info!("Starting injector_core processing"); let injector = Injector::new(); injector.injector_core(request).await } /// Represents a token reference found in a template string #[derive(Debug)] struct TokenReference { /// The field name to be replaced (without the {{$}} wrapper) pub field: String, } /// Parses a single token reference from a string using nom parser combinators /// /// Expects tokens in the format `{{$field_name}}` where field_name contains /// only alphanumeric characters and underscores. fn parse_token(input: &str) -> IResult<&str, TokenReference> { let (input, field) = delimited( tag("{{"), preceded( multispace0, preceded( char('$'), terminated( take_while1(|c: char| c.is_alphanumeric() || c == '_'), multispace0, ), ), ), tag("}}"), )(input)?; Ok(( input, TokenReference { field: field.to_string(), }, )) } /// Finds all token references in a string using nom parser /// /// Scans through the entire input string and extracts all valid token references. /// Returns a vector of TokenReference structs containing the field names. fn find_all_tokens(input: &str) -> Vec<TokenReference> { let mut tokens = Vec::new(); let mut current_input = input; while !current_input.is_empty() { if let Ok((remaining, token_ref)) = parse_token(current_input) { tokens.push(token_ref); current_input = remaining; } else { // Move forward one character if no token found if let Some((_, rest)) = current_input.split_at_checked(1) { current_input = rest; } else { break; } } } tokens } /// Recursively searches for a field in vault data JSON structure /// /// Performs a depth-first search through the JSON object hierarchy to find /// a field with the specified name. Returns the first matching value found. fn find_field_recursively_in_vault_data( obj: &serde_json::Map<String, Value>, field_name: &str, ) -> Option<Value> { obj.get(field_name).cloned().or_else(|| { obj.values() .filter_map(|val| { if let Value::Object(inner_obj) = val { find_field_recursively_in_vault_data(inner_obj, field_name) } else { None } }) .next() }) } #[async_trait] trait TokenInjector { async fn injector_core( &self, request: InjectorRequest, ) -> error_stack::Result<InjectorResponse, InjectorError>; } pub struct Injector; impl Injector { pub fn new() -> Self { Self } /// Processes a string template and replaces token references with vault data #[instrument(skip_all)] fn interpolate_string_template_with_vault_data( &self, template: String, vault_data: &Value, vault_connector: &injector_types::VaultConnectors, ) -> error_stack::Result<String, InjectorError> { // Find all tokens using nom parser let tokens = find_all_tokens(&template); let mut result = template; for token_ref in tokens.into_iter() { let extracted_field_value = self.extract_field_from_vault_data( vault_data, &token_ref.field, vault_connector, )?; let token_str = match extracted_field_value { Value::String(token_value) => token_value, _ => serde_json::to_string(&extracted_field_value).unwrap_or_default(), }; // Replace the token in the result string let token_pattern = format!("{{{{${}}}}}", token_ref.field); result = result.replace(&token_pattern, &token_str); } Ok(result) } #[instrument(skip_all)] fn interpolate_token_references_with_vault_data( &self, value: Value, vault_data: &Value, vault_connector: &injector_types::VaultConnectors, ) -> error_stack::Result<Value, InjectorError> { match value { Value::Object(obj) => { let new_obj = obj .into_iter() .map(|(key, val)| { self.interpolate_token_references_with_vault_data( val, vault_data, vault_connector, ) .map(|processed| (key, processed)) }) .collect::<error_stack::Result<serde_json::Map<_, _>, InjectorError>>()?; Ok(Value::Object(new_obj)) } Value::String(s) => { let processed_string = self.interpolate_string_template_with_vault_data( s, vault_data, vault_connector, )?; Ok(Value::String(processed_string)) } _ => Ok(value), } } #[instrument(skip_all)] fn extract_field_from_vault_data( &self, vault_data: &Value, field_name: &str, vault_connector: &injector_types::VaultConnectors, ) -> error_stack::Result<Value, InjectorError> { logger::debug!( "Extracting field '{}' from vault data using vault type {:?}", field_name, vault_connector ); match vault_data { Value::Object(obj) => { let raw_value = find_field_recursively_in_vault_data(obj, field_name) .ok_or_else(|| { error_stack::Report::new(InjectorError::TokenReplacementFailed( format!("Field '{field_name}' not found"), )) })?; // Apply vault-specific token transformation self.apply_vault_specific_transformation(raw_value, vault_connector, field_name) } _ => Err(error_stack::Report::new( InjectorError::TokenReplacementFailed( "Vault data is not a valid JSON object".to_string(), ), )), } } #[instrument(skip_all)] fn apply_vault_specific_transformation( &self, extracted_field_value: Value, vault_connector: &injector_types::VaultConnectors, field_name: &str, ) -> error_stack::Result<Value, InjectorError> { match vault_connector { injector_types::VaultConnectors::VGS => { logger::debug!( "VGS vault: Using direct token replacement for field '{}'", field_name ); Ok(extracted_field_value) } } } #[instrument(skip_all)] async fn make_http_request( &self, config: &injector_types::ConnectionConfig, payload: &str, content_type: &ContentType, ) -> error_stack::Result<InjectorResponse, InjectorError> { logger::info!( method = ?config.http_method, endpoint = %config.endpoint, content_type = ?content_type, payload_length = payload.len(), headers_count = config.headers.len(), "Making HTTP request to connector" ); // Validate inputs first if config.endpoint.is_empty() { logger::error!("Endpoint URL is empty"); Err(error_stack::Report::new(InjectorError::InvalidTemplate( "Endpoint URL cannot be empty".to_string(), )))?; } // Parse and validate the complete endpoint URL let url = reqwest::Url::parse(&config.endpoint).map_err(|e| { logger::error!("Failed to parse endpoint URL: {}", e); error_stack::Report::new(InjectorError::InvalidTemplate(format!( "Invalid endpoint URL: {e}" ))) })?; logger::debug!("Constructed URL: {}", url); // Convert headers to common_utils Headers format safely let headers: Vec<(String, masking::Maskable<String>)> = config .headers .clone() .into_iter() .map(|(k, v)| (k, masking::Maskable::new_normal(v.expose().clone()))) .collect(); // Determine method and request content let method = Method::from(config.http_method); // Determine request content based on content type with error handling let request_content = match content_type { ContentType::ApplicationJson => { // Try to parse as JSON, fallback to raw string match serde_json::from_str::<Value>(payload) { Ok(json) => Some(RequestContent::Json(Box::new(json))), Err(e) => { logger::debug!( "Failed to parse payload as JSON: {}, falling back to raw bytes", e ); Some(RequestContent::RawBytes(payload.as_bytes().to_vec())) } } } ContentType::ApplicationXWwwFormUrlencoded => { // Parse form data safely let form_data: HashMap<String, String> = url::form_urlencoded::parse(payload.as_bytes()) .into_owned() .collect(); Some(RequestContent::FormUrlEncoded(Box::new(form_data))) } ContentType::ApplicationXml | ContentType::TextXml => { Some(RequestContent::RawBytes(payload.as_bytes().to_vec())) } ContentType::TextPlain => { Some(RequestContent::RawBytes(payload.as_bytes().to_vec())) } }; // Extract vault metadata directly from headers using existing functions let (vault_proxy_url, vault_ca_cert) = if config .headers .contains_key(crate::consts::EXTERNAL_VAULT_METADATA_HEADER) { let mut temp_config = injector_types::ConnectionConfig::new( config.endpoint.clone(), config.http_method, ); // Use existing vault metadata extraction with fallback if temp_config.extract_and_apply_vault_metadata_with_fallback(&config.headers) { (temp_config.proxy_url, temp_config.ca_cert) } else { (None, None) } } else { (None, None) }; // Build request safely with certificate configuration let mut request_builder = RequestBuilder::new() .method(method) .url(url.as_str()) .headers(headers); if let Some(content) = request_content { request_builder = request_builder.set_body(content); } // Create final config with vault CA certificate if available let mut final_config = config.clone(); let has_vault_ca_cert = vault_ca_cert.is_some(); if has_vault_ca_cert { final_config.ca_cert = vault_ca_cert; } // Log certificate configuration (but not the actual content) logger::info!( has_client_cert = final_config.client_cert.is_some(), has_client_key = final_config.client_key.is_some(), has_ca_cert = final_config.ca_cert.is_some(), has_vault_ca_cert = has_vault_ca_cert, insecure = final_config.insecure.unwrap_or(false), cert_format = ?final_config.cert_format, "Certificate configuration applied" ); // Build request with certificate configuration applied let request = build_request_with_certificates(request_builder, &final_config); // Determine which proxy to use: vault metadata > backup > none let final_proxy_url = vault_proxy_url.or_else(|| config.backup_proxy_url.clone()); let proxy = if let Some(proxy_url) = final_proxy_url { let proxy_url_str = proxy_url.expose(); // Set proxy URL for both HTTP and HTTPS traffic Proxy { http_url: Some(proxy_url_str.clone()), https_url: Some(proxy_url_str), idle_pool_connection_timeout: Some(90), bypass_proxy_hosts: None, } } else { Proxy::default() }; // Send request using local standalone http client let response = send_request(&proxy, request, None).await?; // Convert reqwest::Response to InjectorResponse using trait response .into_injector_response() .await .map_err(|e| error_stack::Report::new(e)) } } impl Default for Injector { fn default() -> Self { Self::new() } } #[async_trait] impl TokenInjector for Injector { #[instrument(skip_all)] async fn injector_core( &self, request: InjectorRequest, ) -> error_stack::Result<InjectorResponse, InjectorError> { let start_time = std::time::Instant::now(); // Extract token data from SecretSerdeValue for vault data lookup let vault_data = request.token_data.specific_token_data.expose().clone(); logger::debug!( template_length = request.connector_payload.template.len(), vault_connector = ?request.token_data.vault_connector, "Processing token injection request" ); // Process template string directly with vault-specific logic let processed_payload = self.interpolate_string_template_with_vault_data( request.connector_payload.template, &vault_data, &request.token_data.vault_connector, )?; logger::debug!( processed_payload_length = processed_payload.len(), "Token replacement completed" ); // Determine content type from headers or default to form-urlencoded let content_type = request .connection_config .headers .get("Content-Type") .and_then(|ct| match ct.clone().expose().as_str() { "application/json" => Some(ContentType::ApplicationJson), "application/x-www-form-urlencoded" => { Some(ContentType::ApplicationXWwwFormUrlencoded) } "application/xml" => Some(ContentType::ApplicationXml), "text/xml" => Some(ContentType::TextXml), "text/plain" => Some(ContentType::TextPlain), _ => None, }) .unwrap_or(ContentType::ApplicationXWwwFormUrlencoded); // Make HTTP request to connector and return enhanced response let response = self .make_http_request( &request.connection_config, &processed_payload, &content_type, ) .await?; let elapsed = start_time.elapsed(); logger::info!( duration_ms = elapsed.as_millis(), status_code = response.status_code, response_size = serde_json::to_string(&response.response) .map(|s| s.len()) .unwrap_or(0), headers_count = response.headers.as_ref().map(|h| h.len()).unwrap_or(0), "Token injection completed successfully" ); Ok(response) } } } // Re-export all items pub use core::*; #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use std::collections::HashMap; use router_env::logger; use crate::*; #[tokio::test] #[ignore = "Integration test that requires network access"] async fn test_injector_core_integration() { // Create test request let mut headers = HashMap::new(); headers.insert( "Content-Type".to_string(), masking::Secret::new("application/x-www-form-urlencoded".to_string()), ); headers.insert( "Authorization".to_string(), masking::Secret::new("Bearer Test".to_string()), ); let specific_token_data = common_utils::pii::SecretSerdeValue::new(serde_json::json!({ "card_number": "TEST_123", "cvv": "123", "exp_month": "12", "exp_year": "25" })); let request = InjectorRequest { connector_payload: ConnectorPayload { template: "card_number={{$card_number}}&cvv={{$cvv}}&expiry={{$exp_month}}/{{$exp_year}}&amount=50&currency=USD&transaction_type=purchase".to_string(), }, token_data: TokenData { vault_connector: VaultConnectors::VGS, specific_token_data, }, connection_config: ConnectionConfig { endpoint: "https://api.stripe.com/v1/payment_intents".to_string(), http_method: HttpMethod::POST, headers, proxy_url: None, // Remove proxy that was causing issues backup_proxy_url: None, // Certificate fields (None for basic test) client_cert: None, client_key: None, ca_cert: None, // Empty CA cert for testing insecure: None, cert_password: None, cert_format: None, max_response_size: None, // Use default }, }; // Test the core function - this will make a real HTTP request to httpbin.org let result = injector_core(request).await; // The request should succeed (httpbin.org should be accessible) if let Err(ref e) = result { logger::info!("Error: {e:?}"); } assert!( result.is_ok(), "injector_core should succeed with valid request: {result:?}" ); let response = result.unwrap(); // Print the actual response for demonstration logger::info!("=== HTTP RESPONSE FROM HTTPBIN.ORG ==="); logger::info!( "{}", serde_json::to_string_pretty(&response).unwrap_or_default() ); logger::info!("======================================="); // Response should have a proper status code and response data assert!( response.status_code >= 200 && response.status_code < 300, "Response should have successful status code: {}", response.status_code ); assert!( response.response.is_object() || response.response.is_string(), "Response data should be JSON object or string" ); } #[tokio::test] async fn test_certificate_configuration() { let mut headers = HashMap::new(); headers.insert( "Content-Type".to_string(), masking::Secret::new("application/x-www-form-urlencoded".to_string()), ); headers.insert( "Authorization".to_string(), masking::Secret::new("Bearer TEST".to_string()), ); let specific_token_data = common_utils::pii::SecretSerdeValue::new(serde_json::json!({ "card_number": "4242429789164242", "cvv": "123", "exp_month": "12", "exp_year": "25" })); // Test with insecure flag (skip certificate verification) let request = InjectorRequest { connector_payload: ConnectorPayload { template: "card_number={{$card_number}}&cvv={{$cvv}}&expiry={{$exp_month}}/{{$exp_year}}&amount=50&currency=USD&transaction_type=purchase".to_string(), }, token_data: TokenData { vault_connector: VaultConnectors::VGS, specific_token_data, }, connection_config: ConnectionConfig { endpoint: "https://httpbin.org/post".to_string(), http_method: HttpMethod::POST, headers, proxy_url: None, // Remove proxy to make test work reliably backup_proxy_url: None, // Test without certificates for basic functionality client_cert: None, client_key: None, ca_cert: None, insecure: None, cert_password: None, cert_format: None, max_response_size: None, }, }; let result = injector_core(request).await; // Should succeed even with insecure flag assert!( result.is_ok(), "Certificate test should succeed: {result:?}" ); let response = result.unwrap(); // Print the actual response for demonstration logger::info!("=== CERTIFICATE TEST RESPONSE ==="); logger::info!( "{}", serde_json::to_string_pretty(&response).unwrap_or_default() ); logger::info!("================================"); // Should succeed with proper status code assert!( response.status_code >= 200 && response.status_code < 300, "Certificate test should have successful status code: {}", response.status_code ); // Verify the tokens were replaced correctly in the form data // httpbin.org returns the request data in the 'form' field let response_str = serde_json::to_string(&response.response).unwrap_or_default(); // Check that our test tokens were replaced with the actual values from vault data let tokens_replaced = response_str.contains("4242429789164242") && // card_number response_str.contains("123") && // cvv response_str.contains("12/25"); // expiry assert!( tokens_replaced, "Response should contain replaced tokens (card_number, cvv, expiry): {}", serde_json::to_string_pretty(&response.response).unwrap_or_default() ); } }
{ "crate": "injector", "file": "crates/injector/src/injector.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_injector_-6826520278220561677
clm
file
// Repository: hyperswitch // Crate: injector // File: crates/injector/src/types.rs // Contains: 5 structs, 3 enums pub mod models { use std::collections::HashMap; use async_trait::async_trait; use common_utils::pii::SecretSerdeValue; use masking::Secret; use router_env::logger; use serde::{Deserialize, Serialize}; // Enums for the injector - making it standalone /// Content types supported by the injector for HTTP requests #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ContentType { ApplicationJson, ApplicationXWwwFormUrlencoded, ApplicationXml, TextXml, TextPlain, } /// HTTP methods supported by the injector #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum HttpMethod { GET, POST, PUT, PATCH, DELETE, } /// Vault connectors supported by the injector for token management /// /// Currently supports VGS as the primary vault connector. While only VGS is /// implemented today, this enum structure is maintained for future extensibility /// to support additional vault providers (e.g., Basis Theory, Skyflow, etc.) /// without breaking API compatibility. #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum VaultConnectors { /// VGS (Very Good Security) vault connector VGS, } /// Token data containing vault-specific information for token replacement #[derive(Clone, Debug, Deserialize, Serialize)] pub struct TokenData { /// The specific token data retrieved from the vault pub specific_token_data: SecretSerdeValue, /// The type of vault connector being used (e.g., VGS) pub vault_connector: VaultConnectors, } /// Connector payload containing the template to be processed #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ConnectorPayload { /// Template string containing token references in the format {{$field_name}} pub template: String, } /// Configuration for HTTP connection to the external connector #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ConnectionConfig { /// Complete URL endpoint for the connector (e.g., "https://api.stripe.com/v1/payment_intents") pub endpoint: String, /// HTTP method to use for the request pub http_method: HttpMethod, /// HTTP headers to include in the request pub headers: HashMap<String, Secret<String>>, /// Optional proxy URL for routing the request through a proxy server pub proxy_url: Option<Secret<String>>, /// Optional backup proxy URL to use if vault metadata doesn't provide one #[serde(default)] pub backup_proxy_url: Option<Secret<String>>, /// Optional client certificate for mutual TLS authentication pub client_cert: Option<Secret<String>>, /// Optional client private key for mutual TLS authentication pub client_key: Option<Secret<String>>, /// Optional CA certificate for verifying the server certificate pub ca_cert: Option<Secret<String>>, /// Whether to skip certificate verification (for testing only) pub insecure: Option<bool>, /// Optional password for encrypted client certificate pub cert_password: Option<Secret<String>>, /// Format of the client certificate (e.g., "PEM") pub cert_format: Option<String>, /// Maximum response size in bytes (defaults to 10MB if not specified) pub max_response_size: Option<usize>, } /// Complete request structure for the injector service #[derive(Clone, Debug, Deserialize, Serialize)] pub struct InjectorRequest { /// Token data from the vault pub token_data: TokenData, /// Payload template to process pub connector_payload: ConnectorPayload, /// HTTP connection configuration pub connection_config: ConnectionConfig, } /// Response from the injector including status code and response data #[derive(Clone, Debug, Deserialize, Serialize)] pub struct InjectorResponse { /// HTTP status code from the connector response pub status_code: u16, /// Response headers from the connector (optional) pub headers: Option<HashMap<String, String>>, /// Response body from the connector pub response: serde_json::Value, } /// Trait for converting HTTP responses to InjectorResponse #[async_trait] pub trait IntoInjectorResponse { /// Convert to InjectorResponse with proper error handling async fn into_injector_response( self, ) -> Result<InjectorResponse, crate::injector::core::InjectorError>; } #[async_trait] impl IntoInjectorResponse for reqwest::Response { async fn into_injector_response( self, ) -> Result<InjectorResponse, crate::injector::core::InjectorError> { let status_code = self.status().as_u16(); logger::info!( status_code = status_code, "Converting reqwest::Response to InjectorResponse" ); // Extract headers let headers: Option<HashMap<String, String>> = { let header_map: HashMap<String, String> = self .headers() .iter() .filter_map(|(name, value)| { value .to_str() .ok() .map(|v| (name.to_string(), v.to_string())) }) .collect(); if header_map.is_empty() { None } else { Some(header_map) } }; let response_text = self .text() .await .map_err(|_| crate::injector::core::InjectorError::HttpRequestFailed)?; logger::debug!( response_length = response_text.len(), headers_count = headers.as_ref().map(|h| h.len()).unwrap_or(0), "Processing connector response" ); let response_data = match serde_json::from_str::<serde_json::Value>(&response_text) { Ok(json) => json, Err(_e) => serde_json::Value::String(response_text), }; Ok(InjectorResponse { status_code, headers, response: response_data, }) } } impl InjectorRequest { /// Creates a new InjectorRequest #[allow(clippy::too_many_arguments)] pub fn new( endpoint: String, http_method: HttpMethod, template: String, token_data: TokenData, headers: Option<HashMap<String, Secret<String>>>, proxy_url: Option<Secret<String>>, client_cert: Option<Secret<String>>, client_key: Option<Secret<String>>, ca_cert: Option<Secret<String>>, ) -> Self { let headers = headers.unwrap_or_default(); let mut connection_config = ConnectionConfig::new(endpoint, http_method); // Keep vault metadata header for processing in make_http_request // Store backup proxy for make_http_request to use as fallback connection_config.backup_proxy_url = proxy_url; connection_config.client_cert = connection_config.client_cert.or(client_cert); connection_config.client_key = connection_config.client_key.or(client_key); connection_config.ca_cert = connection_config.ca_cert.or(ca_cert); connection_config.headers = headers; Self { token_data, connector_payload: ConnectorPayload { template }, connection_config, } } } impl ConnectionConfig { /// Creates a new ConnectionConfig from basic parameters pub fn new(endpoint: String, http_method: HttpMethod) -> Self { Self { endpoint, http_method, headers: HashMap::new(), proxy_url: None, backup_proxy_url: None, client_cert: None, client_key: None, ca_cert: None, insecure: None, cert_password: None, cert_format: None, max_response_size: None, } } } } pub use models::*;
{ "crate": "injector", "file": "crates/injector/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_injector_-3615295805829670167
clm
file
// Repository: hyperswitch // Crate: injector // File: crates/injector/src/vault_metadata.rs // Contains: 1 structs, 2 enums use std::collections::HashMap; use base64::Engine; use masking::{ExposeInterface, Secret}; use router_env::logger; use url::Url; use crate::{consts::EXTERNAL_VAULT_METADATA_HEADER, types::ConnectionConfig, VaultConnectors}; const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; /// Trait for different vault metadata processors pub trait VaultMetadataProcessor: Send + Sync { /// Process vault metadata and return connection configuration updates fn process_metadata( &self, connection_config: &mut ConnectionConfig, ) -> Result<(), VaultMetadataError>; /// Get the vault connector type fn vault_connector(&self) -> VaultConnectors; } /// Comprehensive errors related to vault metadata processing #[derive(Debug, thiserror::Error)] pub enum VaultMetadataError { #[error("Failed to decode base64 vault metadata: {0}")] Base64DecodingFailed(String), #[error("Failed to parse vault metadata JSON: {0}")] JsonParsingFailed(String), #[error("Unsupported vault connector: {0}")] UnsupportedVaultConnector(String), #[error("Invalid URL in vault metadata: {0}")] InvalidUrl(String), #[error("Missing required field in vault metadata: {0}")] MissingRequiredField(String), #[error("Invalid certificate format: {0}")] InvalidCertificateFormat(String), #[error("Vault metadata header is empty or malformed")] EmptyOrMalformedHeader, #[error("URL validation failed for {field}: {url} - {reason}")] UrlValidationFailed { field: String, url: String, reason: String, }, #[error("Certificate validation failed: {0}")] CertificateValidationFailed(String), #[error("Vault metadata processing failed for connector {connector}: {reason}")] ProcessingFailed { connector: String, reason: String }, } impl VaultMetadataError { /// Create a URL validation error with context pub fn url_validation_failed(field: &str, url: &str, reason: impl Into<String>) -> Self { Self::UrlValidationFailed { field: field.to_string(), url: url.to_string(), reason: reason.into(), } } } /// External vault proxy metadata (moved from external_services) #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(untagged)] pub enum ExternalVaultProxyMetadata { /// VGS proxy data variant VgsMetadata(VgsMetadata), } /// VGS proxy data (moved from external_services) #[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 VaultMetadataProcessor for VgsMetadata { fn process_metadata( &self, connection_config: &mut ConnectionConfig, ) -> Result<(), VaultMetadataError> { // Validate and set proxy URL from VGS metadata let proxy_url_str = self.proxy_url.as_str().to_string(); connection_config.proxy_url = Some(Secret::new(proxy_url_str.clone())); // Validate and decode certificate from VGS metadata let cert_content = self.certificate.clone().expose(); // Check if certificate is base64 encoded and decode if necessary let decoded_cert = if cert_content.starts_with("-----BEGIN") { cert_content } else { match BASE64_ENGINE.decode(&cert_content) { Ok(decoded_bytes) => String::from_utf8(decoded_bytes).map_err(|e| { VaultMetadataError::CertificateValidationFailed(format!( "Certificate is not valid UTF-8 after base64 decoding: {e}" )) })?, Err(e) => { logger::error!( error = %e, "Failed to decode base64 certificate" ); return Err(VaultMetadataError::CertificateValidationFailed(format!( "Failed to decode base64 certificate: {e}" ))); } } }; connection_config.ca_cert = Some(Secret::new(decoded_cert.clone())); Ok(()) } fn vault_connector(&self) -> VaultConnectors { VaultConnectors::VGS } } impl VaultMetadataProcessor for ExternalVaultProxyMetadata { fn process_metadata( &self, connection_config: &mut ConnectionConfig, ) -> Result<(), VaultMetadataError> { match self { Self::VgsMetadata(vgs_metadata) => vgs_metadata.process_metadata(connection_config), } } fn vault_connector(&self) -> VaultConnectors { match self { Self::VgsMetadata(vgs_metadata) => vgs_metadata.vault_connector(), } } } /// Factory for creating vault metadata processors from different sources pub struct VaultMetadataFactory; impl VaultMetadataFactory { /// Create a vault metadata processor from base64 encoded header value with comprehensive validation pub fn from_base64_header( base64_value: &str, ) -> Result<Box<dyn VaultMetadataProcessor>, VaultMetadataError> { // Validate input if base64_value.trim().is_empty() { return Err(VaultMetadataError::EmptyOrMalformedHeader); } // Decode base64 with detailed error context let decoded_bytes = BASE64_ENGINE.decode(base64_value.trim()).map_err(|e| { logger::error!( error = %e, "Failed to decode base64 vault metadata header" ); VaultMetadataError::Base64DecodingFailed(format!("Invalid base64 encoding: {e}")) })?; // Validate decoded size if decoded_bytes.is_empty() { return Err(VaultMetadataError::EmptyOrMalformedHeader); } if decoded_bytes.len() > 1_000_000 { return Err(VaultMetadataError::JsonParsingFailed( "Decoded vault metadata is too large (>1MB)".to_string(), )); } // Parse JSON with detailed error context let metadata: ExternalVaultProxyMetadata = serde_json::from_slice(&decoded_bytes).map_err(|e| { logger::error!( error = %e, "Failed to parse vault metadata JSON" ); VaultMetadataError::JsonParsingFailed(format!("Invalid JSON structure: {e}")) })?; logger::info!( vault_connector = ?metadata.vault_connector(), "Successfully parsed vault metadata from header" ); Ok(Box::new(metadata)) } } /// Trait for extracting vault metadata from various sources pub trait VaultMetadataExtractor { /// Extract vault metadata from headers and apply to connection config fn extract_and_apply_vault_metadata( &mut self, headers: &HashMap<String, Secret<String>>, ) -> Result<(), VaultMetadataError>; } impl VaultMetadataExtractor for ConnectionConfig { fn extract_and_apply_vault_metadata( &mut self, headers: &HashMap<String, Secret<String>>, ) -> Result<(), VaultMetadataError> { if let Some(vault_metadata_header) = headers.get(EXTERNAL_VAULT_METADATA_HEADER) { let processor = VaultMetadataFactory::from_base64_header(&vault_metadata_header.clone().expose()) .map_err(|e| { logger::error!( error = %e, "Failed to create vault metadata processor from header" ); e })?; processor.process_metadata(self).map_err(|e| { logger::error!( error = %e, vault_connector = ?processor.vault_connector(), "Failed to apply vault metadata to connection config" ); e })?; logger::info!( vault_connector = ?processor.vault_connector(), proxy_url_applied = self.proxy_url.is_some(), ca_cert_applied = self.ca_cert.is_some(), client_cert_applied = self.client_cert.is_some(), "Successfully applied vault metadata to connection configuration" ); } Ok(()) } } /// Extended trait for graceful fallback handling pub trait VaultMetadataExtractorExt { /// Extract vault metadata with graceful fallback (doesn't fail the entire request) fn extract_and_apply_vault_metadata_with_fallback( &mut self, headers: &HashMap<String, Secret<String>>, ) -> bool; /// Extract vault metadata from a single header value with graceful fallback fn extract_and_apply_vault_metadata_with_fallback_from_header( &mut self, header_value: &str, ) -> bool; } impl VaultMetadataExtractorExt for ConnectionConfig { fn extract_and_apply_vault_metadata_with_fallback( &mut self, headers: &HashMap<String, Secret<String>>, ) -> bool { match self.extract_and_apply_vault_metadata(headers) { Ok(()) => { logger::info!( proxy_url_set = self.proxy_url.is_some(), ca_cert_set = self.ca_cert.is_some(), client_cert_set = self.client_cert.is_some(), "Vault metadata processing completed successfully" ); true } Err(error) => { logger::warn!( error = %error, proxy_url_set = self.proxy_url.is_some(), ca_cert_set = self.ca_cert.is_some(), "Vault metadata processing failed, continuing without vault configuration" ); false } } } fn extract_and_apply_vault_metadata_with_fallback_from_header( &mut self, header_value: &str, ) -> bool { let mut temp_headers = HashMap::new(); temp_headers.insert( EXTERNAL_VAULT_METADATA_HEADER.to_string(), Secret::new(header_value.to_string()), ); self.extract_and_apply_vault_metadata_with_fallback(&temp_headers) } } #[cfg(test)] #[allow(clippy::expect_used)] mod tests { use std::collections::HashMap; use base64::Engine; use common_utils::pii::SecretSerdeValue; use super::*; use crate::types::{HttpMethod, InjectorRequest, TokenData, VaultConnectors}; #[test] fn test_vault_metadata_processing() { // Create test VGS metadata with base64 encoded certificate let vgs_metadata = VgsMetadata { proxy_url: "https://vgs-proxy.example.com:8443" .parse() .expect("Valid test URL"), certificate: Secret::new("cert".to_string()), }; let metadata = ExternalVaultProxyMetadata::VgsMetadata(vgs_metadata); // Serialize and base64 encode (as it would come from the header) let metadata_json = serde_json::to_vec(&metadata).expect("Metadata serialization should succeed"); let base64_metadata = BASE64_ENGINE.encode(&metadata_json); // Create headers with vault metadata let mut headers = HashMap::new(); headers.insert( "Content-Type".to_string(), Secret::new("application/json".to_string()), ); headers.insert( "Authorization".to_string(), Secret::new("Bearer token123".to_string()), ); headers.insert( EXTERNAL_VAULT_METADATA_HEADER.to_string(), Secret::new(base64_metadata), ); // Test the amazing automatic processing with the unified API! let injector_request = InjectorRequest::new( "https://api.example.com/v1/payments".to_string(), HttpMethod::POST, "amount={{$amount}}&currency={{$currency}}".to_string(), TokenData { vault_connector: VaultConnectors::VGS, specific_token_data: SecretSerdeValue::new(serde_json::json!({ "amount": "1000", "currency": "USD" })), }, Some(headers), None, // No fallback proxy needed - vault metadata provides it None, // No fallback client cert None, // No fallback client key None, // No fallback CA cert ); // Verify vault metadata was automatically applied! assert!(injector_request.connection_config.proxy_url.is_some()); assert!(injector_request.connection_config.ca_cert.is_some()); assert_eq!( injector_request .connection_config .proxy_url .as_ref() .expect("Proxy URL should be set") .clone() .expose(), "https://vgs-proxy.example.com:8443/" ); // Verify vault metadata header was removed from regular headers assert!(!injector_request .connection_config .headers .contains_key(EXTERNAL_VAULT_METADATA_HEADER)); // Verify other headers are preserved assert!(injector_request .connection_config .headers .contains_key("Content-Type")); assert!(injector_request .connection_config .headers .contains_key("Authorization")); } #[test] fn test_vault_metadata_factory() { let vgs_metadata = VgsMetadata { proxy_url: "https://vgs-proxy.example.com:8443" .parse() .expect("Valid test URL"), certificate: Secret::new("cert".to_string()), }; let metadata = ExternalVaultProxyMetadata::VgsMetadata(vgs_metadata); let metadata_json = serde_json::to_vec(&metadata).expect("Metadata serialization should succeed"); let base64_metadata = BASE64_ENGINE.encode(&metadata_json); // Test factory creation from base64 let processor = VaultMetadataFactory::from_base64_header(&base64_metadata) .expect("Base64 decoding should succeed"); assert_eq!(processor.vault_connector(), VaultConnectors::VGS); // Test processor creation was successful assert!(processor.vault_connector() == VaultConnectors::VGS); } }
{ "crate": "injector", "file": "crates/injector/src/vault_metadata.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_3509942291560686814
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/sqlx.rs // Contains: 1 structs, 0 enums use std::{fmt::Display, str::FromStr}; use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, }; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, }; use diesel_models::enums::{ AttemptStatus, AuthenticationType, Currency, FraudCheckStatus, IntentStatus, PaymentMethod, RefundStatus, RoutingApproach, }; use error_stack::ResultExt; use sqlx::{ postgres::{PgArgumentBuffer, PgPoolOptions, PgRow, PgTypeInfo, PgValueRef}, Decode, Encode, Error::ColumnNotFound, FromRow, Pool, Postgres, Row, }; use storage_impl::config::Database; use time::PrimitiveDateTime; use super::{ health_check::HealthCheck, query::{Aggregate, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, QueryExecutionError, TableEngine, }, }; #[derive(Debug, Clone)] pub struct SqlxClient { pool: Pool<Postgres>, } impl Default for SqlxClient { fn default() -> Self { let database_url = format!( "postgres://{}:{}@{}:{}/{}", "db_user", "db_pass", "localhost", 5432, "hyperswitch_db" ); Self { #[allow(clippy::expect_used)] pool: PgPoolOptions::new() .connect_lazy(&database_url) .expect("SQLX Pool Creation failed"), } } } impl SqlxClient { pub async fn from_conf(conf: &Database, schema: &str) -> Self { let database_url = conf.get_database_url(schema); #[allow(clippy::expect_used)] let pool = PgPoolOptions::new() .max_connections(conf.pool_size) .acquire_timeout(std::time::Duration::from_secs(conf.connection_timeout)) .connect_lazy(&database_url) .expect("SQLX Pool Creation failed"); Self { pool } } } pub trait DbType { fn name() -> &'static str; } macro_rules! db_type { ($a: ident, $str: tt) => { impl DbType for $a { fn name() -> &'static str { stringify!($str) } } }; ($a:ident) => { impl DbType for $a { fn name() -> &'static str { stringify!($a) } } }; } db_type!(Currency); db_type!(AuthenticationType); db_type!(AttemptStatus); db_type!(IntentStatus); db_type!(PaymentMethod, TEXT); db_type!(RefundStatus); db_type!(RefundType); db_type!(FraudCheckStatus); db_type!(FrmTransactionType); db_type!(DisputeStage); db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); db_type!(DecoupledAuthenticationType); db_type!(RoutingApproach); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn encode_by_ref( &self, buf: &mut PgArgumentBuffer, ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> { <String as Encode<'q, Postgres>>::encode(self.0.to_string(), buf) } fn size_hint(&self) -> usize { <String as Encode<'q, Postgres>>::size_hint(&self.0.to_string()) } } impl<'r, Type> Decode<'r, Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn decode( value: PgValueRef<'r>, ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> { let str_value = <&'r str as Decode<'r, Postgres>>::decode(value)?; Type::from_str(str_value).map(DBEnumWrapper).or(Err(format!( "invalid value {:?} for enum {}", str_value, Type::name() ) .into())) } } impl<Type> sqlx::Type<Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn type_info() -> PgTypeInfo { PgTypeInfo::with_name(Type::name()) } } impl<T> LoadRow<T> for SqlxClient where for<'a> T: FromRow<'a, PgRow>, { fn load_row(row: PgRow) -> CustomResult<T, QueryExecutionError> { T::from_row(&row).change_context(QueryExecutionError::RowExtractionFailure) } } impl super::payments::filters::PaymentFilterAnalytics for SqlxClient {} impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {} impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {} impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClient {} impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} impl super::refunds::distribution::RefundDistributionAnalytics for SqlxClient {} impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {} impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {} impl super::frm::filters::FrmFilterAnalytics for SqlxClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for SqlxClient {} impl super::auth_events::filters::AuthEventFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { type Row = PgRow; async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>, { sqlx::query(&format!("{query};")) .fetch_all(&self.pool) .await .change_context(QueryExecutionError::DatabaseError) .attach_printable_lazy(|| format!("Failed to run query {query}"))? .into_iter() .map(Self::load_row) .collect::<Result<Vec<_>, _>>() .change_context(QueryExecutionError::RowExtractionFailure) } } #[async_trait::async_trait] impl HealthCheck for SqlxClient { async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> { sqlx::query("SELECT 1") .fetch_all(&self.pool) .await .map(|_| ()) .change_context(QueryExecutionError::DatabaseError) } } impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = row.try_get("authentication_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let trans_status: Option<DBEnumWrapper<TransactionStatus>> = row.try_get("trans_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row .try_get("authentication_connector") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let message_version: Option<String> = row.try_get("message_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let platform: Option<String> = row.try_get("platform").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_country: Option<String> = row.try_get("merchant_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let billing_country: Option<String> = row.try_get("billing_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let shipping_country: Option<String> = row.try_get("shipping_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_country: Option<String> = row.try_get("issuer_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let earliest_supported_version: Option<String> = row .try_get("earliest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let latest_supported_version: Option<String> = row .try_get("latest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let whitelist_decision: Option<bool> = row.try_get("whitelist_decision").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_manufacturer: Option<String> = row.try_get("device_manufacturer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_display: Option<String> = row.try_get("device_display").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_version: Option<String> = row.try_get("browser_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_requested: Option<bool> = row.try_get("exemption_requested").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_accepted: Option<bool> = row.try_get("exemption_accepted").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, platform, count, start_bucket, end_bucket, 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, }) } } impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = row.try_get("authentication_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let trans_status: Option<DBEnumWrapper<TransactionStatus>> = row.try_get("trans_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row .try_get("authentication_connector") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let message_version: Option<String> = row.try_get("message_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let platform: Option<String> = row.try_get("platform").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_country: Option<String> = row.try_get("merchant_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let billing_country: Option<String> = row.try_get("billing_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let shipping_country: Option<String> = row.try_get("shipping_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_country: Option<String> = row.try_get("issuer_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let earliest_supported_version: Option<String> = row .try_get("earliest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let latest_supported_version: Option<String> = row .try_get("latest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let whitelist_decision: Option<bool> = row.try_get("whitelist_decision").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_manufacturer: Option<String> = row.try_get("device_manufacturer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_display: Option<String> = row.try_get("device_display").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_version: Option<String> = row.try_get("browser_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_requested: Option<bool> = row.try_get("exemption_requested").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_accepted: Option<bool> = row.try_get("exemption_accepted").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, platform, 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, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::frm::metrics::FrmMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = row.try_get("frm_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = row.try_get("frm_transaction_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { frm_name, frm_status, frm_transaction_type, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributionRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, total, count, error_message, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, }) } } impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let status: Option<DBEnumWrapper<IntentStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<i64> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { status, currency, profile_id, connector, authentication_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let status: Option<DBEnumWrapper<IntentStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { status, currency, profile_id, connector, authentication_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, customer_id, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::distribution::RefundDistributionRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, refund_status, connector, refund_type, profile_id, total, count, refund_reason, refund_error_message, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::frm::filters::FrmFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = row.try_get("frm_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = row.try_get("frm_transaction_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { frm_name, frm_status, frm_transaction_type, }) } } impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let dispute_stage: Option<String> = row.try_get("dispute_stage").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let dispute_status: Option<String> = row.try_get("dispute_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector_status: Option<String> = row.try_get("connector_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { dispute_stage, dispute_status, connector, connector_status, currency, }) } } impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let dispute_stage: Option<DBEnumWrapper<DisputeStage>> = row.try_get("dispute_stage").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let dispute_status: Option<DBEnumWrapper<DisputeStatus>> = row.try_get("dispute_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { dispute_stage, dispute_status, connector, currency, total, count, start_bucket, end_bucket, }) } } impl ToSql<SqlxClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) } } impl ToSql<SqlxClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempt".to_string()), Self::PaymentSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("PaymentSessionized table is not implemented for Sqlx"))?, Self::Refund => Ok("refund".to_string()), Self::RefundSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("RefundSessionized table is not implemented for Sqlx"))?, Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("SdkEventsAudit table is not implemented for Sqlx"))?, Self::SdkEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("SdkEvents table is not implemented for Sqlx"))?, Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::FraudCheck => Ok("fraud_check".to_string()), Self::PaymentIntent => Ok("payment_intent".to_string()), Self::PaymentIntentSessionized => Err(error_stack::report!( ParsingError::UnknownError ) .attach_printable("PaymentIntentSessionized table is not implemented for Sqlx"))?, Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, Self::ApiEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::ActivePaymentsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ActivePaymentsAnalytics table is not implemented for Sqlx"))?, Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?, Self::Authentications => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("Authentications table is not implemented for Sqlx"))?, Self::RoutingEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("RoutingEvents table is not implemented for Sqlx"))?, } } } impl<T> ToSql<SqlxClient> for Aggregate<T> where T: ToSql<SqlxClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Count { field: _, alias } => { format!( "count(*){}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Sum { field, alias } => { format!( "sum({}){}", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Min { field, alias } => { format!( "min({}){}", field .to_sql(table_engine) .attach_printable("Failed to min aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Max { field, alias } => { format!( "max({}){}", field .to_sql(table_engine) .attach_printable("Failed to max aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Percentile { field, alias, percentile, } => { format!( "percentile_cont(0.{}) within group (order by {} asc){}", percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()), field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::DistinctCount { field, alias } => { format!( "count(distinct {}){}", field .to_sql(table_engine) .attach_printable("Failed to distinct count aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } impl<T> ToSql<SqlxClient> for Window<T> where T: ToSql<SqlxClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Sum { field, partition_by, order_by, alias, } => { format!( "sum({}) over ({}{}){}", field .to_sql(table_engine) .attach_printable("Failed to sum window")?, partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::RowNumber { field: _, partition_by, order_by, alias, } => { format!( "row_number() over ({}{}){}", partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } }
{ "crate": "analytics", "file": "crates/analytics/src/sqlx.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-2538499979251228972
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/types.rs // Contains: 1 structs, 6 enums use std::{fmt::Display, str::FromStr}; use common_utils::{ errors::{CustomResult, ErrorSwitch, ParsingError}, events::{ApiEventMetric, ApiEventsType}, impl_api_event_type, }; use error_stack::{report, Report, ResultExt}; use super::query::QueryBuildingError; use crate::errors::AnalyticsError; #[derive(serde::Deserialize, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AnalyticsDomain { Payments, Refunds, Frm, PaymentIntents, AuthEvents, SdkEvents, ApiEvents, Dispute, Routing, } #[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)] pub enum AnalyticsCollection { Payment, PaymentSessionized, Refund, RefundSessionized, FraudCheck, SdkEvents, SdkEventsAnalytics, ApiEvents, PaymentIntent, PaymentIntentSessionized, ConnectorEvents, OutgoingWebhookEvent, Authentications, Dispute, DisputeSessionized, ApiEventsAnalytics, ActivePaymentsAnalytics, RoutingEvents, } #[allow(dead_code)] #[derive(Debug)] pub enum TableEngine { CollapsingMergeTree { sign: &'static str }, BasicTree, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, Hash)] #[serde(transparent)] pub struct DBEnumWrapper<T: FromStr + Display>(pub T); impl<T: FromStr + Display> AsRef<T> for DBEnumWrapper<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T: FromStr + Display + Default> Default for DBEnumWrapper<T> { fn default() -> Self { Self(T::default()) } } impl<T> FromStr for DBEnumWrapper<T> where T: FromStr + Display, { type Err = Report<ParsingError>; fn from_str(s: &str) -> Result<Self, Self::Err> { T::from_str(s) .map_err(|_er| report!(ParsingError::EnumParseFailure(std::any::type_name::<T>()))) .map(DBEnumWrapper) .attach_printable_lazy(|| format!("raw_value: {s}")) } } #[async_trait::async_trait] pub trait AnalyticsDataSource where Self: Sized + Sync + Send, { type Row; async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>; fn get_table_engine(_table: AnalyticsCollection) -> TableEngine { TableEngine::BasicTree } } pub trait LoadRow<T> where Self: AnalyticsDataSource, T: Sized, { fn load_row(row: Self::Row) -> CustomResult<T, QueryExecutionError>; } #[derive(thiserror::Error, Debug)] pub enum MetricsError { #[error("Error building query")] QueryBuildingError, #[error("Error running Query")] QueryExecutionFailure, #[error("Error processing query results")] PostProcessingFailure, #[allow(dead_code)] #[error("Not Implemented")] NotImplemented, } #[derive(Debug, thiserror::Error)] pub enum QueryExecutionError { #[error("Failed to extract domain rows")] RowExtractionFailure, #[error("Database error")] DatabaseError, } pub type MetricsResult<T> = CustomResult<T, MetricsError>; impl ErrorSwitch<MetricsError> for QueryBuildingError { fn switch(&self) -> MetricsError { MetricsError::QueryBuildingError } } pub type FiltersResult<T> = CustomResult<T, FiltersError>; #[derive(thiserror::Error, Debug)] pub enum FiltersError { #[error("Error building query")] QueryBuildingError, #[error("Error running Query")] QueryExecutionFailure, #[allow(dead_code)] #[error("Not Implemented: {0}")] NotImplemented(&'static str), } impl ErrorSwitch<FiltersError> for QueryBuildingError { fn switch(&self) -> FiltersError { FiltersError::QueryBuildingError } } impl ErrorSwitch<AnalyticsError> for FiltersError { fn switch(&self) -> AnalyticsError { match self { Self::QueryBuildingError | Self::QueryExecutionFailure => AnalyticsError::UnknownError, Self::NotImplemented(a) => AnalyticsError::NotImplemented(a), } } } impl_api_event_type!(Miscellaneous, (AnalyticsDomain));
{ "crate": "analytics", "file": "crates/analytics/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 6, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_3793240294573717134
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/clickhouse.rs // Contains: 4 structs, 1 enums use std::sync::Arc; use actix_web::http::StatusCode; use common_utils::errors::ParsingError; use error_stack::{report, Report, ResultExt}; use router_env::logger; use time::PrimitiveDateTime; use super::{ active_payments::metrics::ActivePaymentsMetricRow, auth_events::metrics::AuthEventMetricRow, frm::{filters::FrmFilterRow, metrics::FrmMetricRow}, health_check::HealthCheck, payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow}, payments::{ distribution::PaymentDistributionRow, filters::PaymentFilterRow, metrics::PaymentMetricRow, }, query::{Aggregate, ToSql, Window}, refunds::{ distribution::RefundDistributionRow, filters::RefundFilterRow, metrics::RefundMetricRow, }, sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError}, }; use crate::{ api_event::{ events::ApiLogsResult, filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, auth_events::filters::AuthEventFilterRow, connector_events::events::ConnectorEventsResult, disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow}, outgoing_webhook_event::events::OutgoingWebhookLogsResult, routing_events::events::RoutingEventsResult, sdk_events::events::SdkEventsResult, types::TableEngine, }; pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>; #[derive(Clone, Debug)] pub struct ClickhouseClient { pub config: Arc<ClickhouseConfig>, pub database: String, } #[derive(Clone, Debug, serde::Deserialize)] pub struct ClickhouseConfig { username: String, password: Option<String>, host: String, } impl Default for ClickhouseConfig { fn default() -> Self { Self { username: "default".to_string(), password: None, host: "http://localhost:8123".to_string(), } } } impl ClickhouseClient { async fn execute_query(&self, query: &str) -> ClickhouseResult<Vec<serde_json::Value>> { logger::debug!("Executing query: {query}"); let client = reqwest::Client::new(); let params = CkhQuery { date_time_output_format: String::from("iso"), output_format_json_quote_64bit_integers: 0, database: self.database.clone(), }; let response = client .post(&self.config.host) .query(&params) .basic_auth(self.config.username.clone(), self.config.password.clone()) .body(format!("{query}\nFORMAT JSON")) .send() .await .change_context(ClickhouseError::ConnectionError)?; logger::debug!(clickhouse_response=?response, query=?query, "Clickhouse response"); if response.status() != StatusCode::OK { response.text().await.map_or_else( |er| { Err(ClickhouseError::ResponseError) .attach_printable_lazy(|| format!("Error: {er:?}")) }, |t| Err(report!(ClickhouseError::ResponseNotOK(t))), ) } else { Ok(response .json::<CkhOutput<serde_json::Value>>() .await .change_context(ClickhouseError::ResponseError)? .data) } } } #[async_trait::async_trait] impl HealthCheck for ClickhouseClient { async fn deep_health_check( &self, ) -> common_utils::errors::CustomResult<(), QueryExecutionError> { self.execute_query("SELECT 1") .await .map(|_| ()) .change_context(QueryExecutionError::DatabaseError) } } #[async_trait::async_trait] impl AnalyticsDataSource for ClickhouseClient { type Row = serde_json::Value; async fn load_results<T>( &self, query: &str, ) -> common_utils::errors::CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>, { self.execute_query(query) .await .change_context(QueryExecutionError::DatabaseError)? .into_iter() .map(Self::load_row) .collect::<Result<Vec<_>, _>>() .change_context(QueryExecutionError::RowExtractionFailure) } fn get_table_engine(table: AnalyticsCollection) -> TableEngine { match table { AnalyticsCollection::Payment | AnalyticsCollection::PaymentSessionized | AnalyticsCollection::Refund | AnalyticsCollection::RefundSessionized | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent | AnalyticsCollection::PaymentIntentSessionized | AnalyticsCollection::Authentications | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::DisputeSessionized => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::SdkEvents | AnalyticsCollection::SdkEventsAnalytics | AnalyticsCollection::ApiEvents | AnalyticsCollection::ConnectorEvents | AnalyticsCollection::RoutingEvents | AnalyticsCollection::ApiEventsAnalytics | AnalyticsCollection::OutgoingWebhookEvent | AnalyticsCollection::ActivePaymentsAnalytics => TableEngine::BasicTree, } } } impl<T, E> LoadRow<T> for ClickhouseClient where Self::Row: TryInto<T, Error = Report<E>>, { fn load_row(row: Self::Row) -> common_utils::errors::CustomResult<T, QueryExecutionError> { row.try_into() .map_err(|error| error.change_context(QueryExecutionError::RowExtractionFailure)) } } impl super::payments::filters::PaymentFilterAnalytics for ClickhouseClient {} impl super::payments::metrics::PaymentMetricAnalytics for ClickhouseClient {} impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {} impl super::payment_intents::filters::PaymentIntentFilterAnalytics for ClickhouseClient {} impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {} impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} impl super::refunds::distribution::RefundDistributionAnalytics for ClickhouseClient {} impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {} impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {} impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {} impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {} impl super::routing_events::events::RoutingEventLogAnalytics for ClickhouseClient {} impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { } impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {} impl super::disputes::metrics::DisputeMetricAnalytics for ClickhouseClient {} #[derive(Debug, serde::Serialize)] struct CkhQuery { date_time_output_format: String, output_format_json_quote_64bit_integers: u8, database: String, } #[derive(Debug, serde::Deserialize)] struct CkhOutput<T> { data: Vec<T>, } impl TryInto<ApiLogsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiLogsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiLogsResult in clickhouse results", )) } } impl TryInto<SdkEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventsResult in clickhouse results", )) } } impl TryInto<ConnectorEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ConnectorEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ConnectorEventsResult in clickhouse results", )) } } impl TryInto<RoutingEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RoutingEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RoutingEventsResult in clickhouse results", )) } } impl TryInto<PaymentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentMetricRow in clickhouse results", )) } } impl TryInto<PaymentDistributionRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentDistributionRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentDistributionRow in clickhouse results", )) } } impl TryInto<PaymentFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FilterRow in clickhouse results", )) } } impl TryInto<PaymentIntentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentIntentMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentIntentMetricRow in clickhouse results", )) } } impl TryInto<PaymentIntentFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentIntentFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentIntentFilterRow in clickhouse results", )) } } impl TryInto<RefundMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundMetricRow in clickhouse results", )) } } impl TryInto<RefundFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundFilterRow in clickhouse results", )) } } impl TryInto<RefundDistributionRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundDistributionRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundDistributionRow in clickhouse results", )) } } impl TryInto<FrmMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<FrmMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FrmMetricRow in clickhouse results", )) } } impl TryInto<FrmFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<FrmFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FrmFilterRow in clickhouse results", )) } } impl TryInto<DisputeMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<DisputeMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse DisputeMetricRow in clickhouse results", )) } } impl TryInto<DisputeFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<DisputeFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse DisputeFilterRow in clickhouse results", )) } } impl TryInto<ApiEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiEventMetricRow in clickhouse results", )) } } impl TryInto<LatencyAvg> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<LatencyAvg, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse LatencyAvg in clickhouse results", )) } } impl TryInto<SdkEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventMetricRow in clickhouse results", )) } } impl TryInto<SdkEventFilter> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventFilter, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventFilter in clickhouse results", )) } } impl TryInto<AuthEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<AuthEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse AuthEventMetricRow in clickhouse results", )) } } impl TryInto<AuthEventFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<AuthEventFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse AuthEventFilterRow in clickhouse results", )) } } impl TryInto<ApiEventFilter> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiEventFilter, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiEventFilter in clickhouse results", )) } } impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<OutgoingWebhookLogsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse OutgoingWebhookLogsResult in clickhouse results", )) } } impl TryInto<ActivePaymentsMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ActivePaymentsMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ActivePaymentsMetricRow in clickhouse results", )) } } impl ToSql<ClickhouseClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.assume_utc().unix_timestamp().to_string()) } } impl ToSql<ClickhouseClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempts".to_string()), Self::PaymentSessionized => Ok("sessionizer_payment_attempts".to_string()), Self::Refund => Ok("refunds".to_string()), Self::RefundSessionized => Ok("sessionizer_refunds".to_string()), Self::FraudCheck => Ok("fraud_check".to_string()), Self::SdkEvents => Ok("sdk_events_audit".to_string()), Self::SdkEventsAnalytics => Ok("sdk_events".to_string()), Self::ApiEvents => Ok("api_events_audit".to_string()), Self::ApiEventsAnalytics => Ok("api_events".to_string()), Self::PaymentIntent => Ok("payment_intents".to_string()), Self::PaymentIntentSessionized => Ok("sessionizer_payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), Self::Authentications => Ok("authentications".to_string()), Self::RoutingEvents => Ok("routing_events_audit".to_string()), } } } impl<T> ToSql<ClickhouseClient> for Aggregate<T> where T: ToSql<ClickhouseClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Count { field: _, alias } => { let query = match table_engine { TableEngine::CollapsingMergeTree { sign } => format!("sum({sign})"), TableEngine::BasicTree => "count(*)".to_string(), }; format!( "{query}{}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Sum { field, alias } => { let query = match table_engine { TableEngine::CollapsingMergeTree { sign } => format!( "sum({sign} * {})", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")? ), TableEngine::BasicTree => format!( "sum({})", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")? ), }; format!( "{query}{}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Min { field, alias } => { format!( "min({}){}", field .to_sql(table_engine) .attach_printable("Failed to min aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Max { field, alias } => { format!( "max({}){}", field .to_sql(table_engine) .attach_printable("Failed to max aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Percentile { field, alias, percentile, } => { format!( "quantilesExact(0.{})({})[1]{}", percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()), field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::DistinctCount { field, alias } => { format!( "count(distinct {}){}", field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } impl<T> ToSql<ClickhouseClient> for Window<T> where T: ToSql<ClickhouseClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Sum { field, partition_by, order_by, alias, } => { format!( "sum({}) over ({}{}){}", field .to_sql(table_engine) .attach_printable("Failed to sum window")?, partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::RowNumber { field: _, partition_by, order_by, alias, } => { format!( "row_number() over ({}{}){}", partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } #[derive(Debug, thiserror::Error)] pub enum ClickhouseError { #[error("Clickhouse connection error")] ConnectionError, #[error("Clickhouse NON-200 response content: '{0}'")] ResponseNotOK(String), #[error("Clickhouse response error")] ResponseError, }
{ "crate": "analytics", "file": "crates/analytics/src/clickhouse.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_analytics_5886463204261531683
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/lib.rs // Contains: 1 structs, 3 enums pub mod active_payments; pub mod api_event; pub mod auth_events; mod clickhouse; pub mod connector_events; pub mod core; pub mod disputes; pub mod enums; pub mod errors; pub mod frm; pub mod health_check; pub mod metrics; pub mod opensearch; pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; mod query; pub mod refunds; pub mod routing_events; pub mod sdk_events; pub mod search; mod sqlx; mod types; use api_event::metrics::{ApiEventMetric, ApiEventMetricRow}; use common_utils::{errors::CustomResult, types::TenantConfig}; use disputes::metrics::{DisputeMetric, DisputeMetricRow}; use enums::AuthInfo; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use refunds::distribution::{RefundDistribution, RefundDistributionRow}; pub use types::AnalyticsDomain; pub mod lambda_utils; pub mod utils; use std::{collections::HashSet, sync::Arc}; use api_models::analytics::{ active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier}, api_event::{ ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, }, auth_events::{ AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, }, disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier}, payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, PaymentIntentMetricsBucketIdentifier, }, payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier}, sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, }, Granularity, PaymentDistributionBody, RefundDistributionBody, TimeRange, }; use clickhouse::ClickhouseClient; pub use clickhouse::ClickhouseConfig; use error_stack::report; use router_env::{ logger, tracing::{self, instrument}, types::FlowMetric, }; use storage_impl::config::Database; use strum::Display; use self::{ active_payments::metrics::{ActivePaymentsMetric, ActivePaymentsMetricRow}, auth_events::metrics::{AuthEventMetric, AuthEventMetricRow}, frm::metrics::{FrmMetric, FrmMetricRow}, payment_intents::metrics::{PaymentIntentMetric, PaymentIntentMetricRow}, payments::{ distribution::{PaymentDistribution, PaymentDistributionRow}, metrics::{PaymentMetric, PaymentMetricRow}, }, refunds::metrics::{RefundMetric, RefundMetricRow}, sdk_events::metrics::{SdkEventMetric, SdkEventMetricRow}, sqlx::SqlxClient, types::MetricsError, }; #[derive(Clone, Debug)] pub enum AnalyticsProvider { Sqlx(SqlxClient), Clickhouse(ClickhouseClient), CombinedCkh(SqlxClient, ClickhouseClient), CombinedSqlx(SqlxClient, ClickhouseClient), } impl Default for AnalyticsProvider { fn default() -> Self { Self::Sqlx(SqlxClient::default()) } } impl std::fmt::Display for AnalyticsProvider { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let analytics_provider = match self { Self::Clickhouse(_) => "Clickhouse", Self::Sqlx(_) => "Sqlx", Self::CombinedCkh(_, _) => "CombinedCkh", Self::CombinedSqlx(_, _) => "CombinedSqlx", }; write!(f, "{analytics_provider}") } } impl AnalyticsProvider { #[instrument(skip_all)] pub async fn get_payment_metrics( &self, metric: &PaymentMetrics, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics metrics") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics metrics") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_payment_distribution( &self, distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, &distribution.distribution_for, self, ) .await } pub async fn get_payment_intent_metrics( &self, metric: &PaymentIntentMetrics, dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { // Metrics to get the fetch time for each payment intent metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics metrics") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics metrics") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_refund_metrics( &self, metric: &RefundMetrics, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics metrics") } _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics metrics") } _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_refund_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, &distribution.distribution_for, self, ) .await } pub async fn get_frm_metrics( &self, metric: &FrmMetrics, dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, merchant_id, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, merchant_id, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics") } _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics") } _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_dispute_metrics( &self, metric: &DisputeMetrics, dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics metrics") } _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics metrics") } _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_sdk_event_metrics( &self, metric: &SdkEventMetrics, dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( dimensions, publishable_key, filters, granularity, // Since SDK events are ckh only use ckh here time_range, ckh_pool, ) .await } } } pub async fn get_active_payments_metrics( &self, metric: &ActivePaymentsMetrics, merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, time_range: &TimeRange, ) -> types::MetricsResult< HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, > { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric .load_metrics(merchant_id, publishable_key, time_range, pool) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics(merchant_id, publishable_key, time_range, ckh_pool) .await } } } pub async fn get_auth_event_metrics( &self, metric: &AuthEventMetrics, dimensions: &[AuthEventDimensions], auth: &AuthInfo, filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( auth, dimensions, filters, granularity, // Since API events are ckh only use ckh here time_range, ckh_pool, ) .await } } } pub async fn get_api_event_metrics( &self, metric: &ApiEventMetrics, dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { match self { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(ckh_pool) | Self::CombinedCkh(_, ckh_pool) | Self::CombinedSqlx(_, ckh_pool) => { // Since API events are ckh only use ckh here metric .load_metrics( dimensions, merchant_id, filters, granularity, time_range, ckh_pool, ) .await } } } pub async fn from_conf(config: &AnalyticsConfig, tenant: &dyn TenantConfig) -> Self { match config { AnalyticsConfig::Sqlx { sqlx, .. } => { Self::Sqlx(SqlxClient::from_conf(sqlx, tenant.get_schema()).await) } AnalyticsConfig::Clickhouse { clickhouse, .. } => Self::Clickhouse(ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }), AnalyticsConfig::CombinedCkh { sqlx, clickhouse, .. } => Self::CombinedCkh( SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }, ), AnalyticsConfig::CombinedSqlx { sqlx, clickhouse, .. } => Self::CombinedSqlx( SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }, ), } } } #[derive(Clone, Debug, serde::Deserialize)] #[serde(tag = "source", rename_all = "lowercase")] pub enum AnalyticsConfig { Sqlx { sqlx: Database, #[serde(default)] forex_enabled: bool, }, Clickhouse { clickhouse: ClickhouseConfig, #[serde(default)] forex_enabled: bool, }, CombinedCkh { sqlx: Database, clickhouse: ClickhouseConfig, #[serde(default)] forex_enabled: bool, }, CombinedSqlx { sqlx: Database, clickhouse: ClickhouseConfig, #[serde(default)] forex_enabled: bool, }, } impl AnalyticsConfig { pub fn get_forex_enabled(&self) -> bool { match self { Self::Sqlx { forex_enabled, .. } | Self::Clickhouse { forex_enabled, .. } | Self::CombinedCkh { forex_enabled, .. } | Self::CombinedSqlx { forex_enabled, .. } => *forex_enabled, } } } #[async_trait::async_trait] impl SecretsHandler for AnalyticsConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let analytics_config = value.get_inner(); let decrypted_password = match analytics_config { // Todo: Perform kms decryption of clickhouse password Self::Clickhouse { .. } => masking::Secret::new(String::default()), Self::Sqlx { sqlx, .. } | Self::CombinedCkh { sqlx, .. } | Self::CombinedSqlx { sqlx, .. } => { secret_management_client .get_secret(sqlx.password.clone()) .await? } }; Ok(value.transition_state(|conf| match conf { Self::Sqlx { sqlx, forex_enabled, } => Self::Sqlx { sqlx: Database { password: decrypted_password, ..sqlx }, forex_enabled, }, Self::Clickhouse { clickhouse, forex_enabled, } => Self::Clickhouse { clickhouse, forex_enabled, }, Self::CombinedCkh { sqlx, clickhouse, forex_enabled, } => Self::CombinedCkh { sqlx: Database { password: decrypted_password, ..sqlx }, clickhouse, forex_enabled, }, Self::CombinedSqlx { sqlx, clickhouse, forex_enabled, } => Self::CombinedSqlx { sqlx: Database { password: decrypted_password, ..sqlx }, clickhouse, forex_enabled, }, })) } } impl Default for AnalyticsConfig { fn default() -> Self { Self::Sqlx { sqlx: Database::default(), forex_enabled: false, } } } #[derive(Clone, Debug, serde::Deserialize, Default, serde::Serialize)] pub struct ReportConfig { pub payment_function: String, pub refund_function: String, pub dispute_function: String, pub authentication_function: String, pub region: String, } /// Analytics Flow routes Enums /// Info - Dimensions and filters available for the domain /// Filters - Set of values present for the dimension /// Metrics - Analytical data on dimensions and metrics #[derive(Debug, Display, Clone, PartialEq, Eq)] pub enum AnalyticsFlow { GetInfo, GetPaymentMetrics, GetPaymentIntentMetrics, GetRefundsMetrics, GetFrmMetrics, GetSdkMetrics, GetAuthMetrics, GetAuthEventFilters, GetActivePaymentsMetrics, GetPaymentFilters, GetPaymentIntentFilters, GetRefundFilters, GetFrmFilters, GetSdkEventFilters, GetApiEvents, GetSdkEvents, GeneratePaymentReport, GenerateDisputeReport, GenerateRefundReport, GenerateAuthenticationReport, GetApiEventMetrics, GetApiEventFilters, GetConnectorEvents, GetOutgoingWebhookEvents, GetGlobalSearchResults, GetSearchResults, GetDisputeFilters, GetDisputeMetrics, GetSankey, GetRoutingEvents, } impl FlowMetric for AnalyticsFlow {}
{ "crate": "analytics", "file": "crates/analytics/src/lib.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_4658819000549339223
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/query.rs // Contains: 3 structs, 9 enums use std::{fmt, marker::PhantomData}; use api_models::{ analytics::{ self as analytics_api, api_event::ApiEventDimensions, auth_events::{AuthEventDimensions, AuthEventFlows}, disputes::DisputeDimensions, frm::{FrmDimensions, FrmTransactionType}, payment_intents::PaymentIntentDimensions, payments::{PaymentDimensions, PaymentDistributions}, refunds::{RefundDimensions, RefundDistributions, RefundType}, sdk_events::{SdkEventDimensions, SdkEventNames}, Granularity, }, enums::{ AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, IntentStatus, PaymentMethod, PaymentMethodType, RoutingApproach, }, refunds::RefundStatus, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, }; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, }; use diesel_models::{enums as storage_enums, enums::FraudCheckStatus}; use error_stack::ResultExt; use router_env::{logger, Flow}; use super::types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, TableEngine}; use crate::{enums::AuthInfo, types::QueryExecutionError}; pub type QueryResult<T> = error_stack::Result<T, QueryBuildingError>; pub trait QueryFilter<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()>; } pub trait GroupByClause<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_group_by_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()>; } pub trait SeriesBucket { type SeriesType; type GranularityLevel; fn get_lowest_common_granularity_level(&self) -> Self::GranularityLevel; fn get_bucket_size(&self) -> u8; fn clip_to_start( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError>; fn clip_to_end( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError>; } impl<T> QueryFilter<T> for analytics_api::TimeRange where T: AnalyticsDataSource, time::PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { builder.add_custom_filter_clause("created_at", self.start_time, FilterTypes::Gte)?; if let Some(end) = self.end_time { builder.add_custom_filter_clause("created_at", end, FilterTypes::Lte)?; } Ok(()) } } impl GroupByClause<super::SqlxClient> for Granularity { fn set_group_by_clause( &self, builder: &mut QueryBuilder<super::SqlxClient>, ) -> QueryResult<()> { let trunc_scale = self.get_lowest_common_granularity_level(); let granularity_bucket_scale = match self { Self::OneMin => None, Self::FiveMin | Self::FifteenMin | Self::ThirtyMin => Some("minute"), Self::OneHour | Self::OneDay => None, }; let granularity_divisor = self.get_bucket_size(); builder .add_group_by_clause(format!("DATE_TRUNC('{trunc_scale}', created_at)")) .attach_printable("Error adding time prune group by")?; if let Some(scale) = granularity_bucket_scale { builder .add_group_by_clause(format!( "FLOOR(DATE_PART('{scale}', created_at)/{granularity_divisor})" )) .attach_printable("Error adding time binning group by")?; } Ok(()) } } impl GroupByClause<super::ClickhouseClient> for Granularity { fn set_group_by_clause( &self, builder: &mut QueryBuilder<super::ClickhouseClient>, ) -> QueryResult<()> { let interval = match self { Self::OneMin => "toStartOfMinute(created_at)", Self::FiveMin => "toStartOfFiveMinutes(created_at)", Self::FifteenMin => "toStartOfFifteenMinutes(created_at)", Self::ThirtyMin => "toStartOfInterval(created_at, INTERVAL 30 minute)", Self::OneHour => "toStartOfHour(created_at)", Self::OneDay => "toStartOfDay(created_at)", }; builder .add_group_by_clause(interval) .attach_printable("Error adding interval group by") } } #[derive(strum::Display)] #[strum(serialize_all = "lowercase")] pub enum TimeGranularityLevel { Minute, Hour, Day, } impl SeriesBucket for Granularity { type SeriesType = time::PrimitiveDateTime; type GranularityLevel = TimeGranularityLevel; fn get_lowest_common_granularity_level(&self) -> Self::GranularityLevel { match self { Self::OneMin => TimeGranularityLevel::Minute, Self::FiveMin | Self::FifteenMin | Self::ThirtyMin | Self::OneHour => { TimeGranularityLevel::Hour } Self::OneDay => TimeGranularityLevel::Day, } } fn get_bucket_size(&self) -> u8 { match self { Self::OneMin => 60, Self::FiveMin => 5, Self::FifteenMin => 15, Self::ThirtyMin => 30, Self::OneHour => 60, Self::OneDay => 24, } } fn clip_to_start( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError> { let clip_start = |value: u8, modulo: u8| -> u8 { value - value % modulo }; let clipped_time = match ( self.get_lowest_common_granularity_level(), self.get_bucket_size(), ) { (TimeGranularityLevel::Minute, i) => time::Time::MIDNIGHT .replace_second(clip_start(value.second(), i)) .and_then(|t| t.replace_minute(value.minute())) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Hour, i) => time::Time::MIDNIGHT .replace_minute(clip_start(value.minute(), i)) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Day, i) => { time::Time::MIDNIGHT.replace_hour(clip_start(value.hour(), i)) } } .change_context(PostProcessingError::BucketClipping)?; Ok(value.replace_time(clipped_time)) } fn clip_to_end( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError> { let clip_end = |value: u8, modulo: u8| -> u8 { value + modulo - 1 - value % modulo }; let clipped_time = match ( self.get_lowest_common_granularity_level(), self.get_bucket_size(), ) { (TimeGranularityLevel::Minute, i) => time::Time::MIDNIGHT .replace_second(clip_end(value.second(), i)) .and_then(|t| t.replace_minute(value.minute())) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Hour, i) => time::Time::MIDNIGHT .replace_minute(clip_end(value.minute(), i)) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Day, i) => { time::Time::MIDNIGHT.replace_hour(clip_end(value.hour(), i)) } } .change_context(PostProcessingError::BucketClipping) .attach_printable_lazy(|| format!("Bucket Clip Error: {value}"))?; Ok(value.replace_time(clipped_time)) } } #[derive(thiserror::Error, Debug)] pub enum QueryBuildingError { #[allow(dead_code)] #[error("Not Implemented: {0}")] NotImplemented(String), #[error("Failed to Serialize to SQL")] SqlSerializeError, #[error("Failed to build sql query: {0}")] InvalidQuery(&'static str), } #[derive(thiserror::Error, Debug)] pub enum PostProcessingError { #[error("Error Clipping values to bucket sizes")] BucketClipping, } #[derive(Debug)] pub enum Aggregate<R> { Count { field: Option<R>, alias: Option<&'static str>, }, Sum { field: R, alias: Option<&'static str>, }, Min { field: R, alias: Option<&'static str>, }, Max { field: R, alias: Option<&'static str>, }, Percentile { field: R, alias: Option<&'static str>, percentile: Option<&'static u8>, }, DistinctCount { field: R, alias: Option<&'static str>, }, } // Window functions in query // --- // Description - // field: to_sql type value used as expr in aggregation // partition_by: partition by fields in window // order_by: order by fields and order (Ascending / Descending) in window // alias: alias of window expr in query // --- // Usage - // Window::Sum { // field: "count", // partition_by: Some(query_builder.transform_to_sql_values(&dimensions).switch()?), // order_by: Some(("value", Descending)), // alias: Some("total"), // } #[derive(Debug)] pub enum Window<R> { Sum { field: R, partition_by: Option<String>, order_by: Option<(String, Order)>, alias: Option<&'static str>, }, RowNumber { field: R, partition_by: Option<String>, order_by: Option<(String, Order)>, alias: Option<&'static str>, }, } #[derive(Debug, Clone, Copy)] pub enum Order { Ascending, Descending, } impl fmt::Display for Order { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Ascending => write!(f, "asc"), Self::Descending => write!(f, "desc"), } } } // Select TopN values for a group based on a metric // --- // Description - // columns: Columns in group to select TopN values for // count: N in TopN // order_column: metric used to sort and limit TopN // order: sort order of metric (Ascending / Descending) // --- // Usage - // Use via add_top_n_clause fn of query_builder // add_top_n_clause( // &dimensions, // distribution.distribution_cardinality.into(), // "count", // Order::Descending, // ) #[allow(dead_code)] #[derive(Debug)] pub struct TopN { pub columns: String, pub count: u64, pub order_column: String, pub order: Order, } #[derive(Debug, Clone)] pub struct LimitByClause { limit: u64, columns: Vec<String>, } impl fmt::Display for LimitByClause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "LIMIT {} BY {}", self.limit, self.columns.join(", ")) } } #[derive(Debug, Default, Clone, Copy)] pub enum FilterCombinator { #[default] And, Or, } impl<T: AnalyticsDataSource> ToSql<T> for FilterCombinator { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::And => " AND ", Self::Or => " OR ", } .to_owned()) } } #[derive(Debug, Clone)] pub enum Filter { Plain(String, FilterTypes, String), NestedFilter(FilterCombinator, Vec<Filter>), } impl Default for Filter { fn default() -> Self { Self::NestedFilter(FilterCombinator::default(), Vec::new()) } } impl<T: AnalyticsDataSource> ToSql<T> for Filter { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Plain(l, op, r) => filter_type_to_sql(l, *op, r), Self::NestedFilter(operator, filters) => { format!( "( {} )", filters .iter() .map(|f| <Self as ToSql<T>>::to_sql(f, table_engine)) .collect::<Result<Vec<String>, _>>()? .join( <FilterCombinator as ToSql<T>>::to_sql(operator, table_engine)? .as_ref() ) ) } }) } } #[derive(Debug)] pub struct QueryBuilder<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { columns: Vec<String>, filters: Filter, group_by: Vec<String>, order_by: Vec<String>, having: Option<Vec<(String, FilterTypes, String)>>, limit_by: Option<LimitByClause>, outer_select: Vec<String>, top_n: Option<TopN>, table: AnalyticsCollection, distinct: bool, db_type: PhantomData<T>, table_engine: TableEngine, } pub trait ToSql<T: AnalyticsDataSource> { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError>; } impl<T: AnalyticsDataSource> ToSql<T> for &MerchantId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for MerchantId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for &OrganizationId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for ProfileId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for &common_utils::id_type::PaymentId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for bool { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { let flag = *self; Ok(i8::from(flag).to_string()) } } /// Implement `ToSql` on arrays of types that impl `ToString`. macro_rules! impl_to_sql_for_to_string { ($($type:ty),+) => { $( impl<T: AnalyticsDataSource> ToSql<T> for $type { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) } } )+ }; } impl_to_sql_for_to_string!( String, &str, &PaymentDimensions, &PaymentIntentDimensions, &RefundDimensions, &FrmDimensions, PaymentDimensions, PaymentIntentDimensions, &PaymentDistributions, RefundDimensions, &RefundDistributions, FrmDimensions, PaymentMethod, PaymentMethodType, AuthenticationType, Connector, AttemptStatus, IntentStatus, RefundStatus, FraudCheckStatus, storage_enums::RefundStatus, Currency, RefundType, FrmTransactionType, TransactionStatus, AuthenticationStatus, AuthenticationConnectors, DecoupledAuthenticationType, Flow, &String, &bool, &u64, u64, Order, RoutingApproach ); impl_to_sql_for_to_string!( &SdkEventDimensions, SdkEventDimensions, SdkEventNames, AuthEventFlows, &ApiEventDimensions, ApiEventDimensions, &DisputeDimensions, DisputeDimensions, DisputeStage, AuthEventDimensions, &AuthEventDimensions ); #[derive(Debug, Clone, Copy)] pub enum FilterTypes { Equal, NotEqual, EqualBool, In, Gte, Lte, Gt, Like, NotLike, IsNotNull, } pub fn filter_type_to_sql(l: &str, op: FilterTypes, r: &str) -> String { match op { FilterTypes::EqualBool => format!("{l} = {r}"), FilterTypes::Equal => format!("{l} = '{r}'"), FilterTypes::NotEqual => format!("{l} != '{r}'"), FilterTypes::In => format!("{l} IN ({r})"), FilterTypes::Gte => format!("{l} >= '{r}'"), FilterTypes::Gt => format!("{l} > {r}"), FilterTypes::Lte => format!("{l} <= '{r}'"), FilterTypes::Like => format!("{l} LIKE '%{r}%'"), FilterTypes::NotLike => format!("{l} NOT LIKE '%{r}%'"), FilterTypes::IsNotNull => format!("{l} IS NOT NULL"), } } impl<T> QueryBuilder<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { pub fn new(table: AnalyticsCollection) -> Self { Self { columns: Default::default(), filters: Default::default(), group_by: Default::default(), order_by: Default::default(), having: Default::default(), limit_by: Default::default(), outer_select: Default::default(), top_n: Default::default(), table, distinct: Default::default(), db_type: Default::default(), table_engine: T::get_table_engine(table), } } pub fn add_select_column(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.columns.push( column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing select column")?, ); Ok(()) } pub fn transform_to_sql_values(&mut self, values: &[impl ToSql<T>]) -> QueryResult<String> { let res = values .iter() .map(|i| i.to_sql(&self.table_engine)) .collect::<error_stack::Result<Vec<String>, ParsingError>>() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing range filter value")? .join(", "); Ok(res) } pub fn add_top_n_clause( &mut self, columns: &[impl ToSql<T>], count: u64, order_column: impl ToSql<T>, order: Order, ) -> QueryResult<()> where Window<&'static str>: ToSql<T>, { let partition_by_columns = self.transform_to_sql_values(columns)?; let order_by_column = order_column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing select column")?; self.add_outer_select_column(Window::RowNumber { field: "", partition_by: Some(partition_by_columns.clone()), order_by: Some((order_by_column.clone(), order)), alias: Some("top_n"), })?; self.top_n = Some(TopN { columns: partition_by_columns, count, order_column: order_by_column, order, }); Ok(()) } pub fn set_distinct(&mut self) { self.distinct = true } pub fn add_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::Equal) } pub fn add_bool_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::EqualBool) } pub fn add_negative_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::NotEqual) } pub fn add_custom_filter_clause( &mut self, lhs: impl ToSql<T>, rhs: impl ToSql<T>, comparison: FilterTypes, ) -> QueryResult<()> { let filter = Filter::Plain( lhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter key")?, comparison, rhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter value")?, ); self.add_nested_filter_clause(filter); Ok(()) } pub fn add_nested_filter_clause(&mut self, filter: Filter) { match &mut self.filters { Filter::NestedFilter(_, ref mut filters) => filters.push(filter), f @ Filter::Plain(_, _, _) => { self.filters = Filter::NestedFilter(FilterCombinator::And, vec![f.clone(), filter]); } } } pub fn add_filter_in_range_clause( &mut self, key: impl ToSql<T>, values: &[impl ToSql<T>], ) -> QueryResult<()> { let list = values .iter() .map(|i| { // trimming whitespaces from the filter values received in request, to prevent a possibility of an SQL injection i.to_sql(&self.table_engine).map(|s| { let trimmed_str = s.replace(' ', ""); format!("'{trimmed_str}'") }) }) .collect::<error_stack::Result<Vec<String>, ParsingError>>() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing range filter value")? .join(", "); self.add_custom_filter_clause(key, list, FilterTypes::In) } pub fn add_group_by_clause(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.group_by.push( column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing group by field")?, ); Ok(()) } pub fn add_order_by_clause( &mut self, column: impl ToSql<T>, order: impl ToSql<T>, ) -> QueryResult<()> { let column_sql = column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing order by column")?; let order_sql = order .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing order direction")?; self.order_by.push(format!("{column_sql} {order_sql}")); Ok(()) } pub fn set_limit_by(&mut self, limit: u64, columns: &[impl ToSql<T>]) -> QueryResult<()> { let columns = columns .iter() .map(|col| col.to_sql(&self.table_engine)) .collect::<Result<Vec<String>, _>>() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing LIMIT BY columns")?; self.limit_by = Some(LimitByClause { limit, columns }); Ok(()) } pub fn add_granularity_in_mins(&mut self, granularity: Granularity) -> QueryResult<()> { let interval = match granularity { Granularity::OneMin => "1", Granularity::FiveMin => "5", Granularity::FifteenMin => "15", Granularity::ThirtyMin => "30", Granularity::OneHour => "60", Granularity::OneDay => "1440", }; let _ = self.add_select_column(format!( "toStartOfInterval(created_at, INTERVAL {interval} MINUTE) as time_bucket" )); Ok(()) } fn get_filter_clause(&self) -> QueryResult<String> { <Filter as ToSql<T>>::to_sql(&self.filters, &self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) } fn get_select_clause(&self) -> String { self.columns.join(", ") } fn get_group_by_clause(&self) -> String { self.group_by.join(", ") } fn get_outer_select_clause(&self) -> String { self.outer_select.join(", ") } pub fn add_having_clause<R>( &mut self, aggregate: Aggregate<R>, filter_type: FilterTypes, value: impl ToSql<T>, ) -> QueryResult<()> where Aggregate<R>: ToSql<T>, { let aggregate = aggregate .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing having aggregate")?; let value = value .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing having value")?; let entry = (aggregate, filter_type, value); if let Some(having) = &mut self.having { having.push(entry); } else { self.having = Some(vec![entry]); } Ok(()) } pub fn add_outer_select_column(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.outer_select.push( column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing outer select column")?, ); Ok(()) } pub fn get_filter_type_clause(&self) -> Option<String> { self.having.as_ref().map(|vec| { vec.iter() .map(|(l, op, r)| filter_type_to_sql(l, *op, r)) .collect::<Vec<String>>() .join(" AND ") }) } pub fn build_query(&mut self) -> QueryResult<String> where Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { if self.columns.is_empty() { Err(QueryBuildingError::InvalidQuery( "No select fields provided", ))?; } let mut query = String::from("SELECT "); if self.distinct { query.push_str("DISTINCT "); } query.push_str(&self.get_select_clause()); query.push_str(" FROM "); query.push_str( &self .table .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing table value")?, ); let filter_clause = self.get_filter_clause()?; if !filter_clause.is_empty() { query.push_str(" WHERE "); query.push_str(filter_clause.as_str()); } if !self.group_by.is_empty() { query.push_str(" GROUP BY "); query.push_str(&self.get_group_by_clause()); if let TableEngine::CollapsingMergeTree { sign } = self.table_engine { self.add_having_clause( Aggregate::Count { field: Some(sign), alias: None, }, FilterTypes::Gte, "1", )?; } } if self.having.is_some() { if let Some(condition) = self.get_filter_type_clause() { query.push_str(" HAVING "); query.push_str(condition.as_str()); } } if !self.order_by.is_empty() { query.push_str(" ORDER BY "); query.push_str(&self.order_by.join(", ")); } if let Some(limit_by) = &self.limit_by { query.push_str(&format!(" {limit_by}")); } if !self.outer_select.is_empty() { query.insert_str( 0, format!("SELECT {} FROM (", &self.get_outer_select_clause()).as_str(), ); query.push_str(") _"); } if let Some(top_n) = &self.top_n { query.insert_str(0, "SELECT * FROM ("); query.push_str(format!(") _ WHERE top_n <= {}", top_n.count).as_str()); } logger::debug!(%query); Ok(query) } pub async fn execute_query<R, P>( &mut self, store: &P, ) -> CustomResult<CustomResult<Vec<R>, QueryExecutionError>, QueryBuildingError> where P: LoadRow<R> + AnalyticsDataSource, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { let query = self .build_query() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Failed to execute query")?; Ok(store.load_results(query.as_str()).await) } } impl<T> QueryFilter<T> for AuthInfo where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { match self { Self::OrgLevel { org_id } => { builder .add_filter_clause("organization_id", org_id) .attach_printable("Error adding organization_id filter")?; } Self::MerchantLevel { org_id, merchant_ids, } => { builder .add_filter_clause("organization_id", org_id) .attach_printable("Error adding organization_id filter")?; builder .add_filter_in_range_clause("merchant_id", merchant_ids) .attach_printable("Error adding merchant_id filter")?; } Self::ProfileLevel { org_id, merchant_id, profile_ids, } => { builder .add_filter_clause("organization_id", org_id) .attach_printable("Error adding organization_id filter")?; builder .add_filter_clause("merchant_id", merchant_id) .attach_printable("Error adding merchant_id filter")?; builder .add_filter_in_range_clause("profile_id", profile_ids) .attach_printable("Error adding profile_id filter")?; } } Ok(()) } }
{ "crate": "analytics", "file": "crates/analytics/src/query.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 9, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_analytics_7419052918956633980
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/opensearch.rs // Contains: 6 structs, 4 enums use std::collections::HashSet; use api_models::{ analytics::search::SearchIndex, errors::types::{ApiError, ApiErrorResponse}, }; use aws_config::{self, meta::region::RegionProviderChain, Region}; use common_utils::{ errors::{CustomResult, ErrorSwitch}, types::TimeRange, }; use error_stack::ResultExt; use opensearch::{ auth::Credentials, cert::CertificateValidation, cluster::{Cluster, ClusterHealthParts}, http::{ request::JsonBody, response::Response, transport::{SingleNodeConnectionPool, Transport, TransportBuilder}, Url, }, MsearchParts, OpenSearch, SearchParts, }; use serde_json::{json, Map, Value}; use storage_impl::errors::{ApplicationError, StorageError, StorageResult}; use time::PrimitiveDateTime; use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError}; use crate::{enums::AuthInfo, query::QueryBuildingError}; #[derive(Clone, Debug, serde::Deserialize)] #[serde(tag = "auth")] #[serde(rename_all = "lowercase")] pub enum OpenSearchAuth { Basic { username: String, password: String }, Aws { region: String }, } #[derive(Clone, Debug, serde::Deserialize)] pub struct OpenSearchIndexes { pub payment_attempts: String, pub payment_intents: String, pub refunds: String, pub disputes: String, pub sessionizer_payment_attempts: String, pub sessionizer_payment_intents: String, pub sessionizer_refunds: String, pub sessionizer_disputes: String, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)] pub struct OpensearchTimeRange { #[serde(with = "common_utils::custom_serde::iso8601")] pub gte: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub lte: Option<PrimitiveDateTime>, } impl From<TimeRange> for OpensearchTimeRange { fn from(time_range: TimeRange) -> Self { Self { gte: time_range.start_time, lte: time_range.end_time, } } } #[derive(Clone, Debug, serde::Deserialize)] pub struct OpenSearchConfig { host: String, auth: OpenSearchAuth, indexes: OpenSearchIndexes, #[serde(default)] enabled: bool, } impl Default for OpenSearchConfig { fn default() -> Self { Self { host: "https://localhost:9200".to_string(), auth: OpenSearchAuth::Basic { username: "admin".to_string(), password: "admin".to_string(), }, indexes: OpenSearchIndexes { payment_attempts: "hyperswitch-payment-attempt-events".to_string(), payment_intents: "hyperswitch-payment-intent-events".to_string(), refunds: "hyperswitch-refund-events".to_string(), disputes: "hyperswitch-dispute-events".to_string(), sessionizer_payment_attempts: "sessionizer-payment-attempt-events".to_string(), sessionizer_payment_intents: "sessionizer-payment-intent-events".to_string(), sessionizer_refunds: "sessionizer-refund-events".to_string(), sessionizer_disputes: "sessionizer-dispute-events".to_string(), }, enabled: false, } } } #[derive(Debug, thiserror::Error)] pub enum OpenSearchError { #[error("Opensearch is not enabled")] NotEnabled, #[error("Opensearch connection error")] ConnectionError, #[error("Opensearch NON-200 response content: '{0}'")] ResponseNotOK(String), #[error("Opensearch bad request error")] BadRequestError(String), #[error("Opensearch response error")] ResponseError, #[error("Opensearch query building error")] QueryBuildingError, #[error("Opensearch deserialisation error")] DeserialisationError, #[error("Opensearch index access not present error: {0:?}")] IndexAccessNotPermittedError(SearchIndex), #[error("Opensearch unknown error")] UnknownError, #[error("Opensearch access forbidden error")] AccessForbiddenError, } impl ErrorSwitch<OpenSearchError> for QueryBuildingError { fn switch(&self) -> OpenSearchError { OpenSearchError::QueryBuildingError } } impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { fn switch(&self) -> ApiErrorResponse { match self { Self::ConnectionError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 0, "Connection error", None, )), Self::BadRequestError(response) => { ApiErrorResponse::BadRequest(ApiError::new("IR", 1, response.to_string(), None)) } Self::ResponseNotOK(response) => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 1, format!("Something went wrong {response}"), None, )), Self::ResponseError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 2, "Something went wrong", None, )), Self::QueryBuildingError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 3, "Query building error", None, )), Self::DeserialisationError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 4, "Deserialisation error", None, )), Self::IndexAccessNotPermittedError(index) => { ApiErrorResponse::ForbiddenCommonResource(ApiError::new( "IR", 5, format!("Index access not permitted: {index:?}"), None, )) } Self::UnknownError => { ApiErrorResponse::InternalServerError(ApiError::new("IR", 6, "Unknown error", None)) } Self::AccessForbiddenError => ApiErrorResponse::ForbiddenCommonResource(ApiError::new( "IR", 7, "Access Forbidden error", None, )), Self::NotEnabled => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 8, "Opensearch is not enabled", None, )), } } } #[derive(Clone, Debug)] pub struct OpenSearchClient { pub client: OpenSearch, pub transport: Transport, pub indexes: OpenSearchIndexes, } impl OpenSearchClient { pub async fn create(conf: &OpenSearchConfig) -> CustomResult<Self, OpenSearchError> { let url = Url::parse(&conf.host).map_err(|_| OpenSearchError::ConnectionError)?; let transport = match &conf.auth { OpenSearchAuth::Basic { username, password } => { let credentials = Credentials::Basic(username.clone(), password.clone()); TransportBuilder::new(SingleNodeConnectionPool::new(url)) .cert_validation(CertificateValidation::None) .auth(credentials) .build() .map_err(|_| OpenSearchError::ConnectionError)? } OpenSearchAuth::Aws { region } => { let region_provider = RegionProviderChain::first_try(Region::new(region.clone())); let sdk_config = aws_config::from_env().region(region_provider).load().await; let conn_pool = SingleNodeConnectionPool::new(url); TransportBuilder::new(conn_pool) .auth( sdk_config .clone() .try_into() .map_err(|_| OpenSearchError::ConnectionError)?, ) .service_name("es") .build() .map_err(|_| OpenSearchError::ConnectionError)? } }; Ok(Self { transport: transport.clone(), client: OpenSearch::new(transport), indexes: conf.indexes.clone(), }) } pub fn search_index_to_opensearch_index(&self, index: SearchIndex) -> String { match index { SearchIndex::PaymentAttempts => self.indexes.payment_attempts.clone(), SearchIndex::PaymentIntents => self.indexes.payment_intents.clone(), SearchIndex::Refunds => self.indexes.refunds.clone(), SearchIndex::Disputes => self.indexes.disputes.clone(), SearchIndex::SessionizerPaymentAttempts => { self.indexes.sessionizer_payment_attempts.clone() } SearchIndex::SessionizerPaymentIntents => { self.indexes.sessionizer_payment_intents.clone() } SearchIndex::SessionizerRefunds => self.indexes.sessionizer_refunds.clone(), SearchIndex::SessionizerDisputes => self.indexes.sessionizer_disputes.clone(), } } pub async fn execute( &self, query_builder: OpenSearchQueryBuilder, ) -> CustomResult<Response, OpenSearchError> { match query_builder.query_type { OpenSearchQuery::Msearch(ref indexes) => { let payload = query_builder .construct_payload(indexes) .change_context(OpenSearchError::QueryBuildingError)?; let payload_with_indexes = payload.into_iter().zip(indexes).fold( Vec::new(), |mut payload_with_indexes, (index_hit, index)| { payload_with_indexes.push( json!({"index": self.search_index_to_opensearch_index(*index)}).into(), ); payload_with_indexes.push(JsonBody::new(index_hit.clone())); payload_with_indexes }, ); self.client .msearch(MsearchParts::None) .body(payload_with_indexes) .send() .await .change_context(OpenSearchError::ResponseError) } OpenSearchQuery::Search(index) => { let payload = query_builder .clone() .construct_payload(&[index]) .change_context(OpenSearchError::QueryBuildingError)?; let final_payload = payload.first().unwrap_or(&Value::Null); self.client .search(SearchParts::Index(&[ &self.search_index_to_opensearch_index(index) ])) .from(query_builder.offset.unwrap_or(0)) .size(query_builder.count.unwrap_or(10)) .body(final_payload) .send() .await .change_context(OpenSearchError::ResponseError) } } } } #[async_trait::async_trait] impl HealthCheck for OpenSearchClient { async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> { let health = Cluster::new(&self.transport) .health(ClusterHealthParts::None) .send() .await .change_context(QueryExecutionError::DatabaseError)? .json::<OpenSearchHealth>() .await .change_context(QueryExecutionError::DatabaseError)?; if health.status != OpenSearchHealthStatus::Red { Ok(()) } else { Err::<(), error_stack::Report<QueryExecutionError>>( QueryExecutionError::DatabaseError.into(), ) .attach_printable_lazy(|| format!("Opensearch cluster health is red: {health:?}")) } } } impl OpenSearchIndexes { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; when(self.payment_attempts.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Payment Attempts index must not be empty".into(), )) })?; when(self.payment_intents.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Payment Intents index must not be empty".into(), )) })?; when(self.refunds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Refunds index must not be empty".into(), )) })?; when(self.disputes.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Disputes index must not be empty".into(), )) })?; when( self.sessionizer_payment_attempts.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Payment Attempts index must not be empty".into(), )) }, )?; when( self.sessionizer_payment_intents.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Payment Intents index must not be empty".into(), )) }, )?; when(self.sessionizer_refunds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Refunds index must not be empty".into(), )) })?; when(self.sessionizer_disputes.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Disputes index must not be empty".into(), )) })?; Ok(()) } } impl OpenSearchAuth { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; match self { Self::Basic { username, password } => { when(username.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Basic auth username must not be empty".into(), )) })?; when(password.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Basic auth password must not be empty".into(), )) })?; } Self::Aws { region } => { when(region.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Aws auth region must not be empty".into(), )) })?; } }; Ok(()) } } impl OpenSearchConfig { pub async fn get_opensearch_client(&self) -> StorageResult<Option<OpenSearchClient>> { if !self.enabled { return Ok(None); } Ok(Some( OpenSearchClient::create(self) .await .change_context(StorageError::InitializationError)?, )) } pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; if !self.enabled { return Ok(()); } when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch host must not be empty".into(), )) })?; self.indexes.validate()?; self.auth.validate()?; Ok(()) } } #[derive(Debug, serde::Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum OpenSearchHealthStatus { Red, Green, Yellow, } #[derive(Debug, serde::Deserialize)] pub struct OpenSearchHealth { pub status: OpenSearchHealthStatus, } #[derive(Debug, Clone)] pub enum OpenSearchQuery { Msearch(Vec<SearchIndex>), Search(SearchIndex), } #[derive(Debug, Clone)] pub struct OpenSearchQueryBuilder { pub query_type: OpenSearchQuery, pub query: String, pub offset: Option<i64>, pub count: Option<i64>, pub filters: Vec<(String, Vec<Value>)>, pub time_range: Option<OpensearchTimeRange>, search_params: Vec<AuthInfo>, case_sensitive_fields: HashSet<&'static str>, } impl OpenSearchQueryBuilder { pub fn new(query_type: OpenSearchQuery, query: String, search_params: Vec<AuthInfo>) -> Self { Self { query_type, query, search_params, offset: Default::default(), count: Default::default(), filters: Default::default(), time_range: Default::default(), case_sensitive_fields: HashSet::from([ "customer_email.keyword", "search_tags.keyword", "card_last_4.keyword", "payment_id.keyword", "amount", "customer_id.keyword", ]), } } pub fn set_offset_n_count(&mut self, offset: i64, count: i64) -> QueryResult<()> { self.offset = Some(offset); self.count = Some(count); Ok(()) } pub fn set_time_range(&mut self, time_range: OpensearchTimeRange) -> QueryResult<()> { self.time_range = Some(time_range); Ok(()) } pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<Value>) -> QueryResult<()> { self.filters.push((lhs, rhs)); Ok(()) } pub fn get_status_field(&self, index: SearchIndex) -> &str { match index { SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_status.keyword", SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_status.keyword", _ => "status.keyword", } } pub fn get_amount_field(&self, index: SearchIndex) -> &str { match index { SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_amount", SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_amount", _ => "amount", } } pub fn build_filter_array( &self, case_sensitive_filters: Vec<&(String, Vec<Value>)>, index: SearchIndex, ) -> Vec<Value> { let mut filter_array = Vec::new(); if !self.query.is_empty() { filter_array.push(json!({ "multi_match": { "type": "phrase", "query": self.query, "lenient": true } })); } let case_sensitive_json_filters = case_sensitive_filters .into_iter() .map(|(k, v)| { let key = if *k == "amount" { self.get_amount_field(index).to_string() } else { k.clone() }; json!({"terms": {key: v}}) }) .collect::<Vec<Value>>(); filter_array.extend(case_sensitive_json_filters); if let Some(ref time_range) = self.time_range { let range = json!(time_range); filter_array.push(json!({ "range": { "@timestamp": range } })); } filter_array } pub fn build_case_insensitive_filters( &self, mut payload: Value, case_insensitive_filters: &[&(String, Vec<Value>)], auth_array: Vec<Value>, index: SearchIndex, ) -> Value { let mut must_array = case_insensitive_filters .iter() .map(|(k, v)| { let key = if *k == "status.keyword" { self.get_status_field(index).to_string() } else { k.clone() }; json!({ "bool": { "must": [ { "bool": { "should": v.iter().map(|value| { json!({ "term": { format!("{}", key): { "value": value, "case_insensitive": true } } }) }).collect::<Vec<Value>>(), "minimum_should_match": 1 } } ] } }) }) .collect::<Vec<Value>>(); must_array.push(json!({ "bool": { "must": [ { "bool": { "should": auth_array, "minimum_should_match": 1 } } ] }})); if let Some(query) = payload.get_mut("query") { if let Some(bool_obj) = query.get_mut("bool") { if let Some(bool_map) = bool_obj.as_object_mut() { bool_map.insert("must".to_string(), Value::Array(must_array)); } } } payload } pub fn build_auth_array(&self) -> Vec<Value> { self.search_params .iter() .map(|user_level| match user_level { AuthInfo::OrgLevel { org_id } => { let must_clauses = vec![json!({ "term": { "organization_id.keyword": { "value": org_id } } })]; json!({ "bool": { "must": must_clauses } }) } AuthInfo::MerchantLevel { org_id, merchant_ids, } => { let must_clauses = vec![ json!({ "term": { "organization_id.keyword": { "value": org_id } } }), json!({ "terms": { "merchant_id.keyword": merchant_ids } }), ]; json!({ "bool": { "must": must_clauses } }) } AuthInfo::ProfileLevel { org_id, merchant_id, profile_ids, } => { let must_clauses = vec![ json!({ "term": { "organization_id.keyword": { "value": org_id } } }), json!({ "term": { "merchant_id.keyword": { "value": merchant_id } } }), json!({ "terms": { "profile_id.keyword": profile_ids } }), ]; json!({ "bool": { "must": must_clauses } }) } }) .collect::<Vec<Value>>() } /// # Panics /// /// This function will panic if: /// /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types). /// /// Ensure that the input data and the structure of the query are valid and correctly handled. pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> { let mut query_obj = Map::new(); let bool_obj = Map::new(); let (case_sensitive_filters, case_insensitive_filters): (Vec<_>, Vec<_>) = self .filters .iter() .partition(|(k, _)| self.case_sensitive_fields.contains(k.as_str())); let should_array = self.build_auth_array(); query_obj.insert("bool".to_string(), Value::Object(bool_obj.clone())); let mut sort_obj = Map::new(); sort_obj.insert( "@timestamp".to_string(), json!({ "order": "desc" }), ); Ok(indexes .iter() .map(|index| { let mut payload = json!({ "query": query_obj.clone(), "sort": [ Value::Object(sort_obj.clone()) ] }); let filter_array = self.build_filter_array(case_sensitive_filters.clone(), *index); if !filter_array.is_empty() { payload .get_mut("query") .and_then(|query| query.get_mut("bool")) .and_then(|bool_obj| bool_obj.as_object_mut()) .map(|bool_map| { bool_map.insert("filter".to_string(), Value::Array(filter_array)); }); } payload = self.build_case_insensitive_filters( payload, &case_insensitive_filters, should_array.clone(), *index, ); payload }) .collect::<Vec<Value>>()) } }
{ "crate": "analytics", "file": "crates/analytics/src/opensearch.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-3835172182420614150
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/outgoing_webhook_event/events.rs // Contains: 1 structs, 0 enums use api_models::analytics::{outgoing_webhook_event::OutgoingWebhookLogsRequest, Granularity}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, }; pub trait OutgoingWebhookLogsFilterAnalytics: LoadRow<OutgoingWebhookLogsResult> {} pub async fn get_outgoing_webhook_event<T>( merchant_id: &common_utils::id_type::MerchantId, query_param: OutgoingWebhookLogsRequest, pool: &T, ) -> FiltersResult<Vec<OutgoingWebhookLogsResult>> where T: AnalyticsDataSource + OutgoingWebhookLogsFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::OutgoingWebhookEvent); query_builder.add_select_column("*").switch()?; query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder .add_filter_clause("payment_id", &query_param.payment_id) .switch()?; if let Some(event_id) = query_param.event_id { query_builder .add_filter_clause("event_id", &event_id) .switch()?; } if let Some(refund_id) = query_param.refund_id { query_builder .add_filter_clause("refund_id", &refund_id) .switch()?; } if let Some(dispute_id) = query_param.dispute_id { query_builder .add_filter_clause("dispute_id", &dispute_id) .switch()?; } if let Some(mandate_id) = query_param.mandate_id { query_builder .add_filter_clause("mandate_id", &mandate_id) .switch()?; } if let Some(payment_method_id) = query_param.payment_method_id { query_builder .add_filter_clause("payment_method_id", &payment_method_id) .switch()?; } if let Some(attempt_id) = query_param.attempt_id { query_builder .add_filter_clause("attempt_id", &attempt_id) .switch()?; } //TODO!: update the execute_query function to return reports instead of plain errors... query_builder .execute_query::<OutgoingWebhookLogsResult, _>(pool) .await .change_context(FiltersError::QueryBuildingError)? .change_context(FiltersError::QueryExecutionFailure) } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct OutgoingWebhookLogsResult { pub merchant_id: common_utils::id_type::MerchantId, pub event_id: String, pub event_type: String, pub outgoing_webhook_event_type: String, pub payment_id: common_utils::id_type::PaymentId, pub refund_id: Option<String>, pub attempt_id: Option<String>, pub dispute_id: Option<String>, pub payment_method_id: Option<String>, pub mandate_id: Option<String>, pub content: Option<String>, pub is_error: bool, pub error: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, }
{ "crate": "analytics", "file": "crates/analytics/src/outgoing_webhook_event/events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-1051722990843379261
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/payments/distribution.rs // Contains: 1 structs, 0 enums use api_models::analytics::{ payments::{ PaymentDimensions, PaymentDistributions, PaymentFilters, PaymentMetricsBucketIdentifier, }, Granularity, PaymentDistributionBody, TimeRange, }; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; mod payment_error_message; use payment_error_message::PaymentErrorMessage; #[derive(Debug, PartialEq, Eq, serde::Deserialize)] pub struct PaymentDistributionRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub status: Option<DBEnumWrapper<storage_enums::AttemptStatus>>, pub connector: Option<String>, pub authentication_type: Option<DBEnumWrapper<storage_enums::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 first_attempt: Option<bool>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, pub error_message: Option<String>, pub routing_approach: Option<DBEnumWrapper<storage_enums::RoutingApproach>>, pub signature_network: Option<String>, pub is_issuer_regulated: Option<bool>, pub is_debit_routed: Option<bool>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub end_bucket: Option<PrimitiveDateTime>, } pub trait PaymentDistributionAnalytics: LoadRow<PaymentDistributionRow> {} #[async_trait::async_trait] pub trait PaymentDistribution<T> where T: AnalyticsDataSource + PaymentDistributionAnalytics, { #[allow(clippy::too_many_arguments)] async fn load_distribution( &self, distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>>; } #[async_trait::async_trait] impl<T> PaymentDistribution<T> for PaymentDistributions where T: AnalyticsDataSource + PaymentDistributionAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_distribution( &self, distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { match self { Self::PaymentErrorMessage => { PaymentErrorMessage .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } } } }
{ "crate": "analytics", "file": "crates/analytics/src/payments/distribution.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-2461998126094408892
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/payments/metrics.rs // Contains: 1 structs, 0 enums use std::collections::HashSet; use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; mod avg_ticket_size; mod connector_success_rate; mod debit_routing; mod payment_count; mod payment_processed_amount; mod payment_success_count; mod retries_count; mod sessionized_metrics; mod success_rate; use avg_ticket_size::AvgTicketSize; use connector_success_rate::ConnectorSuccessRate; use debit_routing::DebitRouting; use payment_count::PaymentCount; use payment_processed_amount::PaymentProcessedAmount; use payment_success_count::PaymentSuccessCount; use success_rate::PaymentSuccessRate; use self::retries_count::RetriesCount; #[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct PaymentMetricRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub status: Option<DBEnumWrapper<storage_enums::AttemptStatus>>, pub connector: Option<String>, pub authentication_type: Option<DBEnumWrapper<storage_enums::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 first_attempt: Option<bool>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, pub routing_approach: Option<DBEnumWrapper<storage_enums::RoutingApproach>>, pub signature_network: Option<String>, pub is_issuer_regulated: Option<bool>, pub is_debit_routed: Option<bool>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub end_bucket: Option<PrimitiveDateTime>, } pub trait PaymentMetricAnalytics: LoadRow<PaymentMetricRow> {} #[async_trait::async_trait] pub trait PaymentMetric<T> where T: AnalyticsDataSource + PaymentMetricAnalytics, { async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>>; } #[async_trait::async_trait] impl<T> PaymentMetric<T> for PaymentMetrics where T: AnalyticsDataSource + PaymentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { match self { Self::PaymentSuccessRate => { PaymentSuccessRate .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::PaymentCount => { PaymentCount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::PaymentSuccessCount => { PaymentSuccessCount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::PaymentProcessedAmount => { PaymentProcessedAmount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::AvgTicketSize => { AvgTicketSize .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::RetriesCount => { RetriesCount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::ConnectorSuccessRate => { ConnectorSuccessRate .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::DebitRouting => { DebitRouting .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedPaymentSuccessRate => { sessionized_metrics::PaymentSuccessRate .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedPaymentCount => { sessionized_metrics::PaymentCount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedPaymentSuccessCount => { sessionized_metrics::PaymentSuccessCount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedPaymentProcessedAmount => { sessionized_metrics::PaymentProcessedAmount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedAvgTicketSize => { sessionized_metrics::AvgTicketSize .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRetriesCount => { sessionized_metrics::RetriesCount .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedConnectorSuccessRate => { sessionized_metrics::ConnectorSuccessRate .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::PaymentsDistribution => { sessionized_metrics::PaymentsDistribution .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::FailureReasons => { sessionized_metrics::FailureReasons .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedDebitRouting => { sessionized_metrics::DebitRouting .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } } } }
{ "crate": "analytics", "file": "crates/analytics/src/payments/metrics.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-2286518074460733785
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/payments/filters.rs // Contains: 1 structs, 0 enums use api_models::analytics::{payments::PaymentDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{AttemptStatus, AuthenticationType, Currency, RoutingApproach}; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, }, }; pub trait PaymentFilterAnalytics: LoadRow<PaymentFilterRow> {} pub async fn get_payment_filter_for_dimension<T>( dimension: PaymentDimensions, auth: &AuthInfo, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<PaymentFilterRow>> where T: AnalyticsDataSource + PaymentFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); query_builder.add_select_column(dimension).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; auth.set_filter_clause(&mut query_builder).switch()?; query_builder.set_distinct(); query_builder .execute_query::<PaymentFilterRow, _>(pool) .await .change_context(FiltersError::QueryBuildingError)? .change_context(FiltersError::QueryExecutionFailure) } #[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct PaymentFilterRow { pub currency: Option<DBEnumWrapper<Currency>>, pub status: Option<DBEnumWrapper<AttemptStatus>>, pub connector: Option<String>, pub authentication_type: Option<DBEnumWrapper<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 first_attempt: Option<bool>, pub routing_approach: Option<DBEnumWrapper<RoutingApproach>>, pub signature_network: Option<String>, pub is_issuer_regulated: Option<bool>, pub is_debit_routed: Option<bool>, }
{ "crate": "analytics", "file": "crates/analytics/src/payments/filters.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_3905235199153398639
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/payments/accumulator.rs // Contains: 11 structs, 0 enums use api_models::analytics::payments::{ErrorResult, PaymentMetricsBucketValue}; use bigdecimal::ToPrimitive; use diesel_models::enums as storage_enums; use router_env::logger; use super::{distribution::PaymentDistributionRow, metrics::PaymentMetricRow}; #[derive(Debug, Default)] pub struct PaymentMetricsAccumulator { pub payment_success_rate: SuccessRateAccumulator, pub payment_count: CountAccumulator, pub payment_success: CountAccumulator, pub processed_amount: ProcessedAmountAccumulator, pub avg_ticket_size: AverageAccumulator, pub payment_error_message: ErrorDistributionAccumulator, pub retries_count: CountAccumulator, pub retries_amount_processed: RetriesAmountAccumulator, pub connector_success_rate: SuccessRateAccumulator, pub payments_distribution: PaymentsDistributionAccumulator, pub failure_reasons_distribution: FailureReasonsDistributionAccumulator, pub debit_routing: DebitRoutingAccumulator, } #[derive(Debug, Default)] pub struct ErrorDistributionRow { pub count: i64, pub total: i64, pub error_message: String, } #[derive(Debug, Default)] pub struct ErrorDistributionAccumulator { pub error_vec: Vec<ErrorDistributionRow>, } #[derive(Debug, Default)] pub struct FailureReasonsDistributionAccumulator { pub count: u64, pub count_without_retries: u64, } #[derive(Debug, Default)] pub struct SuccessRateAccumulator { pub success: i64, pub total: i64, } #[derive(Debug, Default)] #[repr(transparent)] pub struct CountAccumulator { pub count: Option<i64>, } #[derive(Debug, Default)] pub struct ProcessedAmountAccumulator { pub count_with_retries: Option<i64>, pub total_with_retries: Option<i64>, pub count_without_retries: Option<i64>, pub total_without_retries: Option<i64>, } #[derive(Debug, Default)] pub struct DebitRoutingAccumulator { pub transaction_count: u64, pub savings_amount: u64, } #[derive(Debug, Default)] pub struct AverageAccumulator { pub total: u32, pub count: u32, } #[derive(Debug, Default)] #[repr(transparent)] pub struct RetriesAmountAccumulator { pub total: Option<i64>, } #[derive(Debug, Default)] pub struct PaymentsDistributionAccumulator { pub success: u32, pub failed: u32, pub total: u32, pub success_without_retries: u32, pub success_with_only_retries: u32, pub failed_without_retries: u32, pub failed_with_only_retries: u32, pub total_without_retries: u32, pub total_with_only_retries: u32, } pub trait PaymentMetricAccumulator { type MetricOutput; fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow); fn collect(self) -> Self::MetricOutput; } pub trait PaymentDistributionAccumulator { type DistributionOutput; fn add_distribution_bucket(&mut self, distribution: &PaymentDistributionRow); fn collect(self) -> Self::DistributionOutput; } impl PaymentDistributionAccumulator for ErrorDistributionAccumulator { type DistributionOutput = Option<Vec<ErrorResult>>; fn add_distribution_bucket(&mut self, distribution: &PaymentDistributionRow) { self.error_vec.push(ErrorDistributionRow { count: distribution.count.unwrap_or_default(), total: distribution .total .clone() .map(|i| i.to_i64().unwrap_or_default()) .unwrap_or_default(), error_message: distribution.error_message.clone().unwrap_or("".to_string()), }) } fn collect(mut self) -> Self::DistributionOutput { if self.error_vec.is_empty() { None } else { self.error_vec.sort_by(|a, b| b.count.cmp(&a.count)); let mut res: Vec<ErrorResult> = Vec::new(); for val in self.error_vec.into_iter() { let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0 / f64::from(u32::try_from(val.total).ok()?); res.push(ErrorResult { reason: val.error_message, count: val.count, percentage: (perc * 100.0).round() / 100.0, }) } Some(res) } } } impl PaymentMetricAccumulator for FailureReasonsDistributionAccumulator { type MetricOutput = (Option<u64>, Option<u64>); fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { if let Some(count) = metrics.count { if let Ok(count_u64) = u64::try_from(count) { self.count += count_u64; } } if metrics.first_attempt.unwrap_or(false) { if let Some(count) = metrics.count { if let Ok(count_u64) = u64::try_from(count) { self.count_without_retries += count_u64; } } } } fn collect(self) -> Self::MetricOutput { (Some(self.count), Some(self.count_without_retries)) } } impl PaymentMetricAccumulator for SuccessRateAccumulator { type MetricOutput = Option<f64>; fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { if let Some(ref status) = metrics.status { if status.as_ref() == &storage_enums::AttemptStatus::Charged { self.success += metrics.count.unwrap_or_default(); } }; self.total += metrics.count.unwrap_or_default(); } fn collect(self) -> Self::MetricOutput { if self.total <= 0 { None } else { Some( f64::from(u32::try_from(self.success).ok()?) * 100.0 / f64::from(u32::try_from(self.total).ok()?), ) } } } impl PaymentMetricAccumulator for DebitRoutingAccumulator { type MetricOutput = (Option<u64>, Option<u64>, Option<u64>); fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { if let Some(count) = metrics.count { self.transaction_count += u64::try_from(count).unwrap_or(0); } if let Some(total) = metrics.total.as_ref().and_then(ToPrimitive::to_u64) { self.savings_amount += total; } } fn collect(self) -> Self::MetricOutput { ( Some(self.transaction_count), Some(self.savings_amount), Some(0), ) } } impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { type MetricOutput = ( Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>, ); fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { if let Some(ref status) = metrics.status { if status.as_ref() == &storage_enums::AttemptStatus::Charged { if let Some(success) = metrics .count .and_then(|success| u32::try_from(success).ok()) { self.success += success; if metrics.first_attempt.unwrap_or(false) { self.success_without_retries += success; } else { self.success_with_only_retries += success; } } } if status.as_ref() == &storage_enums::AttemptStatus::Failure { if let Some(failed) = metrics.count.and_then(|failed| u32::try_from(failed).ok()) { self.failed += failed; if metrics.first_attempt.unwrap_or(false) { self.failed_without_retries += failed; } else { self.failed_with_only_retries += failed; } } } if status.as_ref() != &storage_enums::AttemptStatus::AuthenticationFailed && status.as_ref() != &storage_enums::AttemptStatus::PaymentMethodAwaited && status.as_ref() != &storage_enums::AttemptStatus::DeviceDataCollectionPending && status.as_ref() != &storage_enums::AttemptStatus::ConfirmationAwaited && status.as_ref() != &storage_enums::AttemptStatus::Unresolved { if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { self.total += total; if metrics.first_attempt.unwrap_or(false) { self.total_without_retries += total; } else { self.total_with_only_retries += total; } } } } } fn collect(self) -> Self::MetricOutput { if self.total == 0 { (None, None, None, None, None, None) } else { let success = Some(self.success); let success_without_retries = Some(self.success_without_retries); let success_with_only_retries = Some(self.success_with_only_retries); let failed = Some(self.failed); let failed_with_only_retries = Some(self.failed_with_only_retries); let failed_without_retries = Some(self.failed_without_retries); let total = Some(self.total); let total_without_retries = Some(self.total_without_retries); let total_with_only_retries = Some(self.total_with_only_retries); let success_rate = match (success, total) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; let success_rate_without_retries = match (success_without_retries, total_without_retries) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; let success_rate_with_only_retries = match (success_with_only_retries, total_with_only_retries) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; let failed_rate = match (failed, total) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; let failed_rate_without_retries = match (failed_without_retries, total_without_retries) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; let failed_rate_with_only_retries = match (failed_with_only_retries, total_with_only_retries) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; ( success_rate, success_rate_without_retries, success_rate_with_only_retries, failed_rate, failed_rate_without_retries, failed_rate_with_only_retries, ) } } } impl PaymentMetricAccumulator for CountAccumulator { type MetricOutput = Option<u64>; #[inline] fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { self.count = match (self.count, metrics.count) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), } } #[inline] fn collect(self) -> Self::MetricOutput { self.count.and_then(|i| u64::try_from(i).ok()) } } impl PaymentMetricAccumulator for ProcessedAmountAccumulator { type MetricOutput = ( Option<u64>, Option<u64>, Option<u64>, Option<u64>, Option<u64>, Option<u64>, ); #[inline] fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { self.total_with_retries = match ( self.total_with_retries, metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; self.count_with_retries = match (self.count_with_retries, metrics.count) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; if metrics.first_attempt.unwrap_or(false) { self.total_without_retries = match ( self.total_without_retries, metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; self.count_without_retries = match (self.count_without_retries, metrics.count) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; } } #[inline] fn collect(self) -> Self::MetricOutput { let total_with_retries = u64::try_from(self.total_with_retries.unwrap_or(0)).ok(); let count_with_retries = self.count_with_retries.and_then(|i| u64::try_from(i).ok()); let total_without_retries = u64::try_from(self.total_without_retries.unwrap_or(0)).ok(); let count_without_retries = self .count_without_retries .and_then(|i| u64::try_from(i).ok()); ( total_with_retries, count_with_retries, total_without_retries, count_without_retries, Some(0), Some(0), ) } } impl PaymentMetricAccumulator for RetriesAmountAccumulator { type MetricOutput = Option<u64>; fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { self.total = match ( self.total, metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; } #[inline] fn collect(self) -> Self::MetricOutput { u64::try_from(self.total.unwrap_or(0)).ok() } } impl PaymentMetricAccumulator for AverageAccumulator { type MetricOutput = Option<f64>; fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { let total = metrics.total.as_ref().and_then(ToPrimitive::to_u32); let count = metrics.count.and_then(|total| u32::try_from(total).ok()); match (total, count) { (Some(total), Some(count)) => { self.total += total; self.count += count; } _ => { logger::error!(message="Dropping metrics for average accumulator", metric=?metrics); } } } fn collect(self) -> Self::MetricOutput { if self.count == 0 { None } else { Some(f64::from(self.total) / f64::from(self.count)) } } } impl PaymentMetricsAccumulator { pub fn collect(self) -> PaymentMetricsBucketValue { let ( payment_processed_amount, payment_processed_count, payment_processed_amount_without_smart_retries, payment_processed_count_without_smart_retries, payment_processed_amount_in_usd, payment_processed_amount_without_smart_retries_usd, ) = self.processed_amount.collect(); let ( payments_success_rate_distribution, payments_success_rate_distribution_without_smart_retries, payments_success_rate_distribution_with_only_retries, payments_failure_rate_distribution, payments_failure_rate_distribution_without_smart_retries, payments_failure_rate_distribution_with_only_retries, ) = self.payments_distribution.collect(); let (failure_reason_count, failure_reason_count_without_smart_retries) = self.failure_reasons_distribution.collect(); let (debit_routed_transaction_count, debit_routing_savings, debit_routing_savings_in_usd) = self.debit_routing.collect(); PaymentMetricsBucketValue { payment_success_rate: self.payment_success_rate.collect(), payment_count: self.payment_count.collect(), payment_success_count: self.payment_success.collect(), payment_processed_amount, payment_processed_count, payment_processed_amount_without_smart_retries, payment_processed_count_without_smart_retries, avg_ticket_size: self.avg_ticket_size.collect(), payment_error_message: self.payment_error_message.collect(), retries_count: self.retries_count.collect(), retries_amount_processed: self.retries_amount_processed.collect(), connector_success_rate: self.connector_success_rate.collect(), payments_success_rate_distribution, payments_success_rate_distribution_without_smart_retries, payments_success_rate_distribution_with_only_retries, payments_failure_rate_distribution, payments_failure_rate_distribution_without_smart_retries, payments_failure_rate_distribution_with_only_retries, failure_reason_count, failure_reason_count_without_smart_retries, payment_processed_amount_in_usd, payment_processed_amount_without_smart_retries_usd, debit_routed_transaction_count, debit_routing_savings, debit_routing_savings_in_usd, } } }
{ "crate": "analytics", "file": "crates/analytics/src/payments/accumulator.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 11, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-7945299694219812742
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/payments/metrics/connector_success_rate.rs // Contains: 1 structs, 0 enums use std::collections::HashSet; use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct ConnectorSuccessRate; #[async_trait::async_trait] impl<T> super::PaymentMetric<T> for ConnectorSuccessRate where T: AnalyticsDataSource + super::PaymentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); let mut dimensions = dimensions.to_vec(); dimensions.push(PaymentDimensions::PaymentStatus); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; query_builder .add_custom_filter_clause(PaymentDimensions::Connector, "NULL", FilterTypes::IsNotNull) .switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<PaymentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), i.card_network.clone(), i.merchant_id.clone(), i.card_last_4.clone(), i.card_issuer.clone(), i.error_reason.clone(), i.routing_approach.as_ref().map(|i| i.0.clone()), i.signature_network.clone(), i.is_issuer_regulated, i.is_debit_routed, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
{ "crate": "analytics", "file": "crates/analytics/src/payments/metrics/connector_success_rate.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_analytics_-4374625137758179460
clm
file
// Repository: hyperswitch // Crate: analytics // File: crates/analytics/src/payments/metrics/retries_count.rs // Contains: 1 structs, 0 enums use std::collections::HashSet; use api_models::{ analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }, enums::IntentStatus, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct RetriesCount; #[async_trait::async_trait] impl<T> super::PaymentMetric<T> for RetriesCount where T: AnalyticsDataSource + super::PaymentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, _dimensions: &[PaymentDimensions], auth: &AuthInfo, _filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntent); query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Sum { field: "amount", alias: Some("total"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; auth.set_filter_clause(&mut query_builder).switch()?; query_builder .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) .switch()?; query_builder .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) .switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<PaymentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), i.card_network.clone(), i.merchant_id.clone(), i.card_last_4.clone(), i.card_issuer.clone(), i.error_reason.clone(), i.routing_approach.as_ref().map(|i| i.0.clone()), i.signature_network.clone(), i.is_issuer_regulated, i.is_debit_routed, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
{ "crate": "analytics", "file": "crates/analytics/src/payments/metrics/retries_count.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }