repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch | crates/external_services/README.md | .md | # External Services
This crate includes interactions with external systems, which may be shared
across crates within this workspace.
| 24 | 2,306 |
hyperswitch | crates/external_services/src/email.rs | .rs | //! Interactions with the AWS SES SDK
use aws_sdk_sesv2::types::Body;
use common_utils::{errors::CustomResult, pii};
use serde::Deserialize;
/// Implementation of aws ses client
pub mod ses;
/// Implementation of SMTP server client
pub mod smtp;
/// Implementation of Email client when email support is disabled
pub mod no_email;
/// Custom Result type alias for Email operations.
pub type EmailResult<T> = CustomResult<T, EmailError>;
/// A trait that defines the methods that must be implemented to send email.
#[async_trait::async_trait]
pub trait EmailClient: Sync + Send + dyn_clone::DynClone {
/// The rich text type of the email client
type RichText;
/// Sends an email to the specified recipient with the given subject and body.
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
proxy_url: Option<&String>,
) -> EmailResult<()>;
/// Convert Stringified HTML to client native rich text format
/// This has to be done because not all clients may format html as the same
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError>
where
Self::RichText: Send;
}
/// A super trait which is automatically implemented for all EmailClients
#[async_trait::async_trait]
pub trait EmailService: Sync + Send + dyn_clone::DynClone {
/// Compose and send email using the email data
async fn compose_and_send_email(
&self,
base_url: &str,
email_data: Box<dyn EmailData + Send>,
proxy_url: Option<&String>,
) -> EmailResult<()>;
}
#[async_trait::async_trait]
impl<T> EmailService for T
where
T: EmailClient,
<Self as EmailClient>::RichText: Send,
{
async fn compose_and_send_email(
&self,
base_url: &str,
email_data: Box<dyn EmailData + Send>,
proxy_url: Option<&String>,
) -> EmailResult<()> {
let email_data = email_data.get_email_data(base_url);
let email_data = email_data.await?;
let EmailContents {
subject,
body,
recipient,
} = email_data;
let rich_text_string = self.convert_to_rich_text(body)?;
self.send_email(recipient, subject, rich_text_string, proxy_url)
.await
}
}
/// This is a struct used to create Intermediate String for rich text ( html )
#[derive(Debug)]
pub struct IntermediateString(String);
impl IntermediateString {
/// Create a new Instance of IntermediateString using a string
pub fn new(inner: String) -> Self {
Self(inner)
}
/// Get the inner String
pub fn into_inner(self) -> String {
self.0
}
}
/// Temporary output for the email subject
#[derive(Debug)]
pub struct EmailContents {
/// The subject of email
pub subject: String,
/// This will be the intermediate representation of the email body in a generic format.
/// The email clients can convert this intermediate representation to their client specific rich text format
pub body: IntermediateString,
/// The email of the recipient to whom the email has to be sent
pub recipient: pii::Email,
}
/// A trait which will contain the logic of generating the email subject and body
#[async_trait::async_trait]
pub trait EmailData {
/// Get the email contents
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError>;
}
dyn_clone::clone_trait_object!(EmailClient<RichText = Body>);
/// List of available email clients to choose from
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(tag = "active_email_client")]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EmailClientConfigs {
#[default]
/// Default Email client to use when no client is specified
NoEmailClient,
/// AWS ses email client
Ses {
/// AWS SES client configuration
aws_ses: ses::SESConfig,
},
/// Other Simple SMTP server
Smtp {
/// SMTP server configuration
smtp: smtp::SmtpServerConfig,
},
}
/// Struct that contains the settings required to construct an EmailClient.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct EmailSettings {
/// The AWS region to send SES requests to.
pub aws_region: String,
/// Number of days for verification of the email
pub allowed_unverified_days: i64,
/// Sender email
pub sender_email: String,
#[serde(flatten)]
/// The client specific configurations
pub client_config: EmailClientConfigs,
/// Recipient email for recon emails
pub recon_recipient_email: pii::Email,
/// Recipient email for recon emails
pub prod_intent_recipient_email: pii::Email,
}
impl EmailSettings {
/// Validation for the Email client specific configurations
pub fn validate(&self) -> Result<(), &'static str> {
match &self.client_config {
EmailClientConfigs::Ses { ref aws_ses } => aws_ses.validate(),
EmailClientConfigs::Smtp { ref smtp } => smtp.validate(),
EmailClientConfigs::NoEmailClient => Ok(()),
}
}
}
/// Errors that could occur from EmailClient.
#[derive(Debug, thiserror::Error)]
pub enum EmailError {
/// An error occurred when building email client.
#[error("Error building email client")]
ClientBuildingFailure,
/// An error occurred when sending email
#[error("Error sending email to recipient")]
EmailSendingFailure,
/// Failed to generate the email token
#[error("Failed to generate email token")]
TokenGenerationFailure,
/// The expected feature is not implemented
#[error("Feature not implemented")]
NotImplemented,
/// An error occurred when building email content.
#[error("Error building email content")]
ContentBuildFailure,
}
| 1,306 | 2,307 |
hyperswitch | crates/external_services/src/hashicorp_vault.rs | .rs | //! Interactions with the HashiCorp Vault
pub mod core;
pub mod implementers;
| 19 | 2,308 |
hyperswitch | crates/external_services/src/managers.rs | .rs | //! Config and client managers
pub mod encryption_management;
pub mod secrets_management;
| 16 | 2,309 |
hyperswitch | crates/external_services/src/file_storage.rs | .rs | //! Module for managing file storage operations with support for multiple storage schemes.
use std::{
fmt::{Display, Formatter},
sync::Arc,
};
use common_utils::errors::CustomResult;
/// Includes functionality for AWS S3 storage operations.
#[cfg(feature = "aws_s3")]
mod aws_s3;
mod file_system;
/// Enum representing different file storage configurations, allowing for multiple storage schemes.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "file_storage_backend")]
#[serde(rename_all = "snake_case")]
pub enum FileStorageConfig {
/// AWS S3 storage configuration.
#[cfg(feature = "aws_s3")]
AwsS3 {
/// Configuration for AWS S3 file storage.
aws_s3: aws_s3::AwsFileStorageConfig,
},
/// Local file system storage configuration.
#[default]
FileSystem,
}
impl FileStorageConfig {
/// Validates the file storage configuration.
pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
match self {
#[cfg(feature = "aws_s3")]
Self::AwsS3 { aws_s3 } => aws_s3.validate(),
Self::FileSystem => Ok(()),
}
}
/// Retrieves the appropriate file storage client based on the file storage configuration.
pub async fn get_file_storage_client(&self) -> Arc<dyn FileStorageInterface> {
match self {
#[cfg(feature = "aws_s3")]
Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await),
Self::FileSystem => Arc::new(file_system::FileSystem),
}
}
}
/// Trait for file storage operations
#[async_trait::async_trait]
pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send {
/// Uploads a file to the selected storage scheme.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError>;
/// Deletes a file from the selected storage scheme.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError>;
/// Retrieves a file from the selected storage scheme.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>;
}
dyn_clone::clone_trait_object!(FileStorageInterface);
/// Error thrown when the file storage config is invalid
#[derive(Debug, Clone)]
pub struct InvalidFileStorageConfig(&'static str);
impl std::error::Error for InvalidFileStorageConfig {}
impl Display for InvalidFileStorageConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "file_storage: {}", self.0)
}
}
/// Represents errors that can occur during file storage operations.
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum FileStorageError {
/// Indicates that the file upload operation failed.
#[error("Failed to upload file")]
UploadFailed,
/// Indicates that the file retrieval operation failed.
#[error("Failed to retrieve file")]
RetrieveFailed,
/// Indicates that the file deletion operation failed.
#[error("Failed to delete file")]
DeleteFailed,
}
| 694 | 2,310 |
hyperswitch | crates/external_services/src/grpc_client.rs | .rs | /// Dyanimc Routing Client interface implementation
#[cfg(feature = "dynamic_routing")]
pub mod dynamic_routing;
/// gRPC based Heath Check Client interface implementation
#[cfg(feature = "dynamic_routing")]
pub mod health_check_client;
use std::{fmt::Debug, sync::Arc};
#[cfg(feature = "dynamic_routing")]
use common_utils::consts;
#[cfg(feature = "dynamic_routing")]
use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy};
#[cfg(feature = "dynamic_routing")]
use health_check_client::HealthCheckClient;
#[cfg(feature = "dynamic_routing")]
use http_body_util::combinators::UnsyncBoxBody;
#[cfg(feature = "dynamic_routing")]
use hyper::body::Bytes;
#[cfg(feature = "dynamic_routing")]
use hyper_util::client::legacy::connect::HttpConnector;
#[cfg(feature = "dynamic_routing")]
use router_env::logger;
use serde;
#[cfg(feature = "dynamic_routing")]
use tonic::Status;
#[cfg(feature = "dynamic_routing")]
/// Hyper based Client type for maintaining connection pool for all gRPC services
pub type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>;
/// Struct contains all the gRPC Clients
#[derive(Debug, Clone)]
pub struct GrpcClients {
/// The routing client
#[cfg(feature = "dynamic_routing")]
pub dynamic_routing: RoutingStrategy,
/// Health Check client for all gRPC services
#[cfg(feature = "dynamic_routing")]
pub health_client: HealthCheckClient,
}
/// 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: DynamicRoutingClientConfig,
}
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(feature = "dynamic_routing")]
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()
.get_dynamic_routing_connection(client.clone())
.await
.expect("Failed to establish a connection with the Dynamic Routing Server");
#[cfg(feature = "dynamic_routing")]
let health_client = HealthCheckClient::build_connections(self, client)
.await
.expect("Failed to build gRPC connections");
Arc::new(GrpcClients {
#[cfg(feature = "dynamic_routing")]
dynamic_routing: dynamic_routing_connection,
#[cfg(feature = "dynamic_routing")]
health_client,
})
}
}
/// Contains grpc headers
#[derive(Debug)]
pub struct GrpcHeaders {
/// Tenant id
pub tenant_id: String,
/// Request id
pub request_id: Option<String>,
}
#[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!(dynamic_routing_request=?request);
request
}
| 1,034 | 2,311 |
hyperswitch | crates/external_services/src/lib.rs | .rs | //! Interactions with external systems.
#![warn(missing_docs, missing_debug_implementations)]
#[cfg(feature = "email")]
pub mod email;
#[cfg(feature = "aws_kms")]
pub mod aws_kms;
pub mod file_storage;
#[cfg(feature = "hashicorp-vault")]
pub mod hashicorp_vault;
pub mod no_encryption;
/// Building grpc clients to communicate with the server
pub mod grpc_client;
pub mod managers;
/// Crate specific constants
#[cfg(feature = "aws_kms")]
pub mod consts {
/// General purpose base64 engine
pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose =
base64::engine::general_purpose::STANDARD;
}
/// Metrics for interactions with external systems.
#[cfg(feature = "aws_kms")]
pub mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES");
#[cfg(feature = "aws_kms")]
counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures
#[cfg(feature = "aws_kms")]
counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS decryption time (in sec)
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS encryption time (in sec)
}
| 362 | 2,312 |
hyperswitch | crates/external_services/src/aws_kms.rs | .rs | //! Interactions with the AWS KMS SDK
pub mod core;
pub mod implementers;
| 19 | 2,313 |
hyperswitch | crates/external_services/src/no_encryption.rs | .rs | //! No encryption functionalities
pub mod core;
pub mod implementers;
| 14 | 2,314 |
hyperswitch | crates/external_services/src/grpc_client/dynamic_routing.rs | .rs | /// 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: Option<SuccessRateCalculatorClient<Client>>,
/// contract based routing service for Dynamic Routing
pub contract_based_client: Option<ContractScoreCalculatorClient<Client>>,
/// elimination service for Dynamic Routing
pub elimination_based_client: Option<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 async fn get_dynamic_routing_connection(
self,
client: Client,
) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
let (success_rate_client, contract_based_client, elimination_based_client) = 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");
(
Some(SuccessRateCalculatorClient::with_origin(
client.clone(),
uri.clone(),
)),
Some(ContractScoreCalculatorClient::with_origin(
client.clone(),
uri.clone(),
)),
Some(EliminationAnalyserClient::with_origin(client, uri)),
)
}
Self::Disabled => (None, None, None),
};
Ok(RoutingStrategy {
success_rate_client,
contract_based_client,
elimination_based_client,
})
}
}
| 774 | 2,315 |
hyperswitch | crates/external_services/src/grpc_client/health_check_client.rs | .rs | use std::{collections::HashMap, fmt::Debug};
use api_models::health_check::{HealthCheckMap, HealthCheckServices};
use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
use error_stack::ResultExt;
pub use health_check::{
health_check_response::ServingStatus, health_client::HealthClient, HealthCheckRequest,
HealthCheckResponse,
};
use router_env::logger;
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod health_check {
tonic::include_proto!("grpc.health.v1");
}
use super::{Client, DynamicRoutingClientConfig, GrpcClientSettings};
/// Result type for Dynamic Routing
pub type HealthCheckResult<T> = CustomResult<T, HealthCheckError>;
/// Dynamic Routing Errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckError {
/// The required input is missing
#[error("Missing fields: {0} for building the Health check connection")]
MissingFields(String),
/// Error from gRPC Server
#[error("Error from gRPC Server : {0}")]
ConnectionError(String),
/// status is invalid
#[error("Invalid Status from server")]
InvalidStatus,
}
/// Health Check Client type
#[derive(Debug, Clone)]
pub struct HealthCheckClient {
/// Health clients for all gRPC based services
pub clients: HashMap<HealthCheckServices, HealthClient<Client>>,
}
impl HealthCheckClient {
/// Build connections to all gRPC services
pub async fn build_connections(
config: &GrpcClientSettings,
client: Client,
) -> Result<Self, Box<dyn std::error::Error>> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
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 {
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)
}
}
| 997 | 2,316 |
hyperswitch | crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs | .rs | use api_models::routing::{
CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, SuccessRateSpecificityLevel,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
pub use success_rate::{
success_rate_calculator_client::SuccessRateCalculatorClient, CalGlobalSuccessRateConfig,
CalGlobalSuccessRateRequest, CalGlobalSuccessRateResponse, CalSuccessRateConfig,
CalSuccessRateRequest, CalSuccessRateResponse,
CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
InvalidateWindowsResponse, LabelWithStatus,
SuccessRateSpecificityLevel as ProtoSpecificityLevel, UpdateSuccessRateWindowConfig,
UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod success_rate {
tonic::include_proto!("success_rate");
}
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
use crate::grpc_client::{self, GrpcHeaders};
/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window
#[async_trait::async_trait]
pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
/// To calculate the success rate for the list of chosen connectors
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse>;
/// To update the success rate with the given label
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
/// To invalidates the success rate routing keys
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse>;
/// To calculate both global and merchant specific success rate for the list of chosen connectors
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse>;
}
#[async_trait::async_trait]
impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
#[instrument(skip_all)]
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalSuccessRateRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let labels_with_status = label_input
.clone()
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.to_string(),
status: conn_choice.status,
})
.collect();
let global_labels_with_status = label_input
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.connector.to_string(),
status: conn_choice.status,
})
.collect();
let request = grpc_client::create_grpc_request(
UpdateSuccessRateWindowRequest {
id,
params,
labels_with_status,
config,
global_labels_with_status,
},
headers,
);
let response = self
.clone()
.update_success_rate_window(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to update the success rate window".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse> {
let request = grpc_client::create_grpc_request(InvalidateWindowsRequest { id }, headers);
let response = self
.clone()
.invalidate_windows(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to invalidate the success rate routing keys".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse> {
let labels = label_input
.clone()
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let global_labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.connector.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalGlobalSuccessRateRequest {
entity_id: id,
entity_params: params,
entity_labels: labels,
global_labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_entity_and_global_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the entity and global success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
}
impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> {
Ok(Self {
duration_in_mins: current_threshold.duration_in_mins,
max_total_count: current_threshold
.max_total_count
.get_required_value("max_total_count")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "max_total_count".to_string(),
})?,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
max_aggregates_size: config
.max_aggregates_size
.get_required_value("max_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "max_aggregates_size".to_string(),
})?,
current_block_threshold: config
.current_block_threshold
.map(ForeignTryFrom::foreign_try_from)
.transpose()?,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
specificity_level: match config.specificity_level {
SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()),
SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()),
},
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalGlobalSuccessRateConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
entity_min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
entity_default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
})
}
}
| 2,275 | 2,317 |
hyperswitch | crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs | .rs | use api_models::routing::{
ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,
LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
};
use common_utils::{
ext_traits::OptionExt,
transformers::{ForeignFrom, ForeignTryFrom},
};
pub use contract_routing::{
contract_score_calculator_client::ContractScoreCalculatorClient, CalContractScoreConfig,
CalContractScoreRequest, CalContractScoreResponse, InvalidateContractRequest,
InvalidateContractResponse, LabelInformation as ProtoLabelInfo, TimeScale,
UpdateContractRequest, UpdateContractResponse,
};
use error_stack::ResultExt;
use router_env::logger;
use crate::grpc_client::{self, GrpcHeaders};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod contract_routing {
tonic::include_proto!("contract_routing");
}
pub use tonic::Code;
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
/// The trait ContractBasedDynamicRouting would have the functions required to support the calculation and updation window
#[async_trait::async_trait]
pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
/// To calculate the contract scores for the list of chosen connectors
async fn calculate_contract_score(
&self,
id: String,
config: ContractBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalContractScoreResponse>;
/// To update the contract scores with the given labels
async fn update_contracts(
&self,
id: String,
label_info: Vec<LabelInformation>,
params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
incr_count: u64,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateContractResponse>;
/// To invalidates the contract scores against the id
async fn invalidate_contracts(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateContractResponse>;
}
#[async_trait::async_trait]
impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {
async fn calculate_contract_score(
&self,
id: String,
config: ContractBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalContractScoreResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalContractScoreRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_contract_score(request)
.await
.map_err(|err| match err.code() {
Code::NotFound => DynamicRoutingError::ContractNotFound,
_ => DynamicRoutingError::ContractBasedRoutingFailure(err.to_string()),
})?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn update_contracts(
&self,
id: String,
label_info: Vec<LabelInformation>,
params: String,
_response: Vec<RoutableConnectorChoiceWithStatus>,
incr_count: u64,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateContractResponse> {
let mut labels_information = label_info
.into_iter()
.map(ProtoLabelInfo::foreign_from)
.collect::<Vec<_>>();
labels_information
.iter_mut()
.for_each(|info| info.current_count += incr_count);
let request = grpc_client::create_grpc_request(
UpdateContractRequest {
id,
params,
labels_information,
},
headers,
);
let response = self
.clone()
.update_contract(request)
.await
.change_context(DynamicRoutingError::ContractBasedRoutingFailure(
"Failed to update the contracts".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn invalidate_contracts(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateContractResponse> {
let request = grpc_client::create_grpc_request(InvalidateContractRequest { id }, headers);
let response = self
.clone()
.invalidate_contract(request)
.await
.change_context(DynamicRoutingError::ContractBasedRoutingFailure(
"Failed to invalidate the contracts".to_string(),
))?
.into_inner();
Ok(response)
}
}
impl ForeignFrom<ContractBasedTimeScale> for TimeScale {
fn foreign_from(scale: ContractBasedTimeScale) -> Self {
Self {
time_scale: match scale {
ContractBasedTimeScale::Day => 0,
_ => 1,
},
}
}
}
impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
constants: config
.constants
.get_required_value("constants")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "constants".to_string(),
})?,
time_scale: config.time_scale.clone().map(TimeScale::foreign_from),
})
}
}
impl ForeignFrom<LabelInformation> for ProtoLabelInfo {
fn foreign_from(config: LabelInformation) -> Self {
Self {
label: format!(
"{}:{}",
config.label.clone(),
config.mca_id.get_string_repr()
),
target_count: config.target_count,
target_time: config.target_time,
current_count: u64::default(),
}
}
}
| 1,333 | 2,318 |
hyperswitch | crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs | .rs | use api_models::routing::{
EliminationAnalyserConfig as EliminationConfig, RoutableConnectorChoice,
RoutableConnectorChoiceWithBucketName,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
pub use elimination_rate::{
elimination_analyser_client::EliminationAnalyserClient, EliminationBucketConfig,
EliminationRequest, EliminationResponse, InvalidateBucketRequest, InvalidateBucketResponse,
LabelWithBucketName, UpdateEliminationBucketRequest, UpdateEliminationBucketResponse,
};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod elimination_rate {
tonic::include_proto!("elimination");
}
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
use crate::grpc_client::{self, GrpcHeaders};
/// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket
#[async_trait::async_trait]
pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync {
/// To perform the elimination based routing for the list of connectors
async fn perform_elimination_routing(
&self,
id: String,
params: String,
labels: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse>;
/// To update the bucket size and ttl for list of connectors with its respective bucket name
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
config: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse>;
/// To invalidate the previous id's bucket
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse>;
}
#[async_trait::async_trait]
impl EliminationBasedRouting for EliminationAnalyserClient<Client> {
#[instrument(skip_all)]
async fn perform_elimination_routing(
&self,
id: String,
params: String,
label_input: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let request = grpc_client::create_grpc_request(
EliminationRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.get_elimination_status(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to perform the elimination analysis".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse> {
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let labels_with_bucket_name = report
.into_iter()
.map(|conn_choice_with_bucket| LabelWithBucketName {
label: conn_choice_with_bucket
.routable_connector_choice
.to_string(),
bucket_name: conn_choice_with_bucket.bucket_name,
})
.collect::<Vec<_>>();
let request = grpc_client::create_grpc_request(
UpdateEliminationBucketRequest {
id,
params,
labels_with_bucket_name,
config,
},
headers,
);
let response = self
.clone()
.update_elimination_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to update the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse> {
let request = grpc_client::create_grpc_request(InvalidateBucketRequest { id }, headers);
let response = self
.clone()
.invalidate_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to invalidate the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
}
impl ForeignTryFrom<EliminationConfig> for EliminationBucketConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: EliminationConfig) -> Result<Self, Self::Error> {
Ok(Self {
bucket_size: config
.bucket_size
.get_required_value("bucket_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_size".to_string(),
})?,
bucket_leak_interval_in_secs: config
.bucket_leak_interval_in_secs
.get_required_value("bucket_leak_interval_in_secs")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_leak_interval_in_secs".to_string(),
})?,
})
}
}
| 1,273 | 2,319 |
hyperswitch | crates/external_services/src/managers/secrets_management.rs | .rs | //! Secrets management util module
use common_utils::errors::CustomResult;
#[cfg(feature = "hashicorp-vault")]
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::{
SecretManagementInterface, SecretsManagementError,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
#[cfg(feature = "hashicorp-vault")]
use crate::hashicorp_vault;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for secrets management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "secrets_manager")]
#[serde(rename_all = "snake_case")]
pub enum SecretsManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// HashiCorp-Vault configuration
#[cfg(feature = "hashicorp-vault")]
HashiCorpVault {
/// HC-Vault config
hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl SecretsManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => hc_vault.validate(),
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate secret management client based on the configuration.
pub async fn get_secret_management_client(
&self,
) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => {
Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await))
}
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => {
hashicorp_vault::core::HashiCorpVault::new(hc_vault)
.change_context(SecretsManagementError::ClientCreationFailed)
.map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })
}
Self::NoEncryption => Ok(Box::new(NoEncryption)),
}
}
}
| 565 | 2,320 |
hyperswitch | crates/external_services/src/managers/encryption_management.rs | .rs | //! Encryption management util module
use std::sync::Arc;
use common_utils::errors::CustomResult;
use hyperswitch_interfaces::encryption_interface::{
EncryptionError, EncryptionManagementInterface,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for encryption management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "encryption_manager")]
#[serde(rename_all = "snake_case")]
pub enum EncryptionManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl EncryptionManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate encryption client based on the configuration.
pub async fn get_encryption_management_client(
&self,
) -> CustomResult<Arc<dyn EncryptionManagementInterface>, EncryptionError> {
Ok(match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
Self::NoEncryption => Arc::new(NoEncryption),
})
}
}
| 359 | 2,321 |
hyperswitch | crates/external_services/src/hashicorp_vault/core.rs | .rs | //! Interactions with the HashiCorp Vault
use std::{collections::HashMap, future::Future, pin::Pin};
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
use error_stack::{Report, ResultExt};
use masking::{PeekInterface, Secret};
use vaultrs::client::{VaultClient, VaultClientSettingsBuilder};
static HC_CLIENT: tokio::sync::OnceCell<HashiCorpVault> = tokio::sync::OnceCell::const_new();
#[allow(missing_debug_implementations)]
/// A struct representing a connection to HashiCorp Vault.
pub struct HashiCorpVault {
/// The underlying client used for interacting with HashiCorp Vault.
client: VaultClient,
}
/// Configuration for connecting to HashiCorp Vault.
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[serde(default)]
pub struct HashiCorpVaultConfig {
/// The URL of the HashiCorp Vault server.
pub url: String,
/// The authentication token used to access HashiCorp Vault.
pub token: Secret<String>,
}
impl HashiCorpVaultConfig {
/// Verifies that the [`HashiCorpVault`] configuration is usable.
pub fn validate(&self) -> Result<(), &'static str> {
when(self.url.is_default_or_empty(), || {
Err("HashiCorp vault url must not be empty")
})?;
when(self.token.is_default_or_empty(), || {
Err("HashiCorp vault token must not be empty")
})
}
}
/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration.
///
/// # Parameters
///
/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
pub async fn get_hashicorp_client(
config: &HashiCorpVaultConfig,
) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> {
HC_CLIENT
.get_or_try_init(|| async { HashiCorpVault::new(config) })
.await
}
/// A trait defining an engine for interacting with HashiCorp Vault.
pub trait Engine: Sized {
/// The associated type representing the return type of the engine's operations.
type ReturnType<'b, T>
where
T: 'b,
Self: 'b;
/// Reads data from HashiCorp Vault at the specified location.
///
/// # Parameters
///
/// - `client`: A reference to the HashiCorpVault client.
/// - `location`: The location in HashiCorp Vault to read data from.
///
/// # Returns
///
/// A future representing the result of the read operation.
fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String>;
}
/// An implementation of the `Engine` trait for the Key-Value version 2 (Kv2) engine.
#[derive(Debug)]
pub enum Kv2 {}
impl Engine for Kv2 {
type ReturnType<'b, T: 'b> =
Pin<Box<dyn Future<Output = error_stack::Result<T, HashiCorpError>> + Send + 'b>>;
fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String> {
Box::pin(async move {
let mut split = location.split(':');
let mount = split.next().ok_or(HashiCorpError::IncompleteData)?;
let path = split.next().ok_or(HashiCorpError::IncompleteData)?;
let key = split.next().unwrap_or("value");
let mut output =
vaultrs::kv2::read::<HashMap<String, String>>(&client.client, mount, path)
.await
.map_err(Into::<Report<_>>::into)
.change_context(HashiCorpError::FetchFailed)?;
Ok(output.remove(key).ok_or(HashiCorpError::ParseError)?)
})
}
}
impl HashiCorpVault {
/// Creates a new instance of HashiCorpVault based on the provided configuration.
///
/// # Parameters
///
/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> {
VaultClient::new(
VaultClientSettingsBuilder::default()
.address(&config.url)
.token(config.token.peek())
.build()
.map_err(Into::<Report<_>>::into)
.change_context(HashiCorpError::ClientCreationFailed)
.attach_printable("Failed while building vault settings")?,
)
.map_err(Into::<Report<_>>::into)
.change_context(HashiCorpError::ClientCreationFailed)
.map(|client| Self { client })
}
/// Asynchronously fetches data from HashiCorp Vault using the specified engine.
///
/// # Parameters
///
/// - `data`: A String representing the location or identifier of the data in HashiCorp Vault.
///
/// # Type Parameters
///
/// - `En`: The engine type that implements the `Engine` trait.
/// - `I`: The type that can be constructed from the retrieved encoded data.
pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError>
where
for<'a> En: Engine<
ReturnType<'a, String> = Pin<
Box<
dyn Future<Output = error_stack::Result<String, HashiCorpError>>
+ Send
+ 'a,
>,
>,
> + 'a,
I: FromEncoded,
{
let output = En::read(self, data).await?;
I::from_encoded(output).ok_or(error_stack::report!(HashiCorpError::HexDecodingFailed))
}
}
/// A trait for types that can be constructed from encoded data in the form of a String.
pub trait FromEncoded: Sized {
/// Constructs an instance of the type from the provided encoded input.
///
/// # Parameters
///
/// - `input`: A String containing the encoded data.
///
/// # Returns
///
/// An `Option<Self>` representing the constructed instance if successful, or `None` otherwise.
///
/// # Example
///
/// ```rust
/// use external_services::hashicorp_vault::core::FromEncoded;
/// use masking::Secret;
/// let secret_instance = Secret::<String>::from_encoded("encoded_secret_string".to_string());
/// let vec_instance = Vec::<u8>::from_encoded("68656c6c6f".to_string());
/// ```
fn from_encoded(input: String) -> Option<Self>;
}
impl FromEncoded for Secret<String> {
fn from_encoded(input: String) -> Option<Self> {
Some(input.into())
}
}
impl FromEncoded for Vec<u8> {
fn from_encoded(input: String) -> Option<Self> {
hex::decode(input).ok()
}
}
/// An enumeration representing various errors that can occur in interactions with HashiCorp Vault.
#[derive(Debug, thiserror::Error)]
pub enum HashiCorpError {
/// Failed while creating hashicorp client
#[error("Failed while creating a new client")]
ClientCreationFailed,
/// Failed while building configurations for hashicorp client
#[error("Failed while building configuration")]
ConfigurationBuildFailed,
/// Failed while decoding data to hex format
#[error("Failed while decoding hex data")]
HexDecodingFailed,
/// An error occurred when base64 decoding input data.
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
/// An error occurred when KMS decrypting input data.
#[error("Failed to KMS decrypt input data")]
DecryptionFailed,
/// The KMS decrypted output does not include a plaintext output.
#[error("Missing plaintext KMS decryption output")]
MissingPlaintextDecryptionOutput,
/// An error occurred UTF-8 decoding KMS decrypted output.
#[error("Failed to UTF-8 decode decryption output")]
Utf8DecodingFailed,
/// Incomplete data provided to fetch data from hasicorp
#[error("Provided information about the value is incomplete")]
IncompleteData,
/// Failed while fetching data from vault
#[error("Failed while fetching data from the server")]
FetchFailed,
/// Failed while parsing received data
#[error("Failed while parsing the response")]
ParseError,
}
| 1,832 | 2,322 |
hyperswitch | crates/external_services/src/hashicorp_vault/implementers.rs | .rs | //! Trait implementations for Hashicorp vault client
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::{
SecretManagementInterface, SecretsManagementError,
};
use masking::{ExposeInterface, Secret};
use crate::hashicorp_vault::core::{HashiCorpVault, Kv2};
#[async_trait::async_trait]
impl SecretManagementInterface for HashiCorpVault {
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
self.fetch::<Kv2, Secret<String>>(input.expose())
.await
.map(|val| val.expose().to_owned())
.change_context(SecretsManagementError::FetchSecretFailed)
.map(Into::into)
}
}
| 176 | 2,323 |
hyperswitch | crates/external_services/src/email/ses.rs | .rs | use std::time::{Duration, SystemTime};
use aws_sdk_sesv2::{
config::Region,
operation::send_email::SendEmailError,
types::{Body, Content, Destination, EmailContent, Message},
Client,
};
use aws_sdk_sts::config::Credentials;
use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
use common_utils::{errors::CustomResult, pii};
use error_stack::{report, ResultExt};
use hyper::Uri;
use masking::PeekInterface;
use router_env::logger;
use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
/// Client for AWS SES operation
#[derive(Debug, Clone)]
pub struct AwsSes {
sender: String,
ses_config: SESConfig,
settings: EmailSettings,
}
/// Struct that contains the AWS ses specific configs required to construct an SES email client
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct SESConfig {
/// The arn of email role
pub email_role_arn: String,
/// The name of sts_session role
pub sts_role_session_name: String,
}
impl SESConfig {
/// Validation for the SES client specific configs
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.email_role_arn.is_default_or_empty(), || {
Err("email.aws_ses.email_role_arn must not be empty")
})?;
when(self.sts_role_session_name.is_default_or_empty(), || {
Err("email.aws_ses.sts_role_session_name must not be empty")
})
}
}
/// Errors that could occur during SES operations.
#[derive(Debug, thiserror::Error)]
pub enum AwsSesError {
/// An error occurred in the SDK while sending email.
#[error("Failed to Send Email {0:?}")]
SendingFailure(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(AwsSesError::SendingFailure)
.change_context(EmailError::EmailSendingFailure)?;
Ok(())
}
}
| 1,812 | 2,324 |
hyperswitch | crates/external_services/src/email/smtp.rs | .rs | use std::time::Duration;
use common_utils::{errors::CustomResult, pii};
use error_stack::ResultExt;
use lettre::{
address::AddressError,
error,
message::{header::ContentType, Mailbox},
transport::smtp::{self, authentication::Credentials},
Message, SmtpTransport, Transport,
};
use masking::{PeekInterface, Secret};
use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
/// Client for SMTP server operation
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct SmtpServer {
/// sender email id
pub sender: String,
/// SMTP server specific configs
pub smtp_config: SmtpServerConfig,
}
impl SmtpServer {
/// A helper function to create SMTP server client
pub fn create_client(&self) -> Result<SmtpTransport, SmtpError> {
let host = self.smtp_config.host.clone();
let port = self.smtp_config.port;
let timeout = Some(Duration::from_secs(self.smtp_config.timeout));
let credentials = self
.smtp_config
.username
.clone()
.zip(self.smtp_config.password.clone())
.map(|(username, password)| {
Credentials::new(username.peek().to_owned(), password.peek().to_owned())
});
match &self.smtp_config.connection {
SmtpConnection::StartTls => match credentials {
Some(credentials) => Ok(SmtpTransport::starttls_relay(&host)
.map_err(SmtpError::ConnectionFailure)?
.port(port)
.timeout(timeout)
.credentials(credentials)
.build()),
None => Ok(SmtpTransport::starttls_relay(&host)
.map_err(SmtpError::ConnectionFailure)?
.port(port)
.timeout(timeout)
.build()),
},
SmtpConnection::Plaintext => match credentials {
Some(credentials) => Ok(SmtpTransport::builder_dangerous(&host)
.port(port)
.timeout(timeout)
.credentials(credentials)
.build()),
None => Ok(SmtpTransport::builder_dangerous(&host)
.port(port)
.timeout(timeout)
.build()),
},
}
}
/// Constructs a new SMTP client
pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self {
Self {
sender: conf.sender_email.clone(),
smtp_config: smtp_config.clone(),
}
}
/// helper function to convert email id into Mailbox
fn to_mail_box(email: String) -> EmailResult<Mailbox> {
Ok(Mailbox::new(
None,
email
.parse()
.map_err(SmtpError::EmailParsingFailed)
.change_context(EmailError::EmailSendingFailure)?,
))
}
}
/// Struct that contains the SMTP server specific configs required
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct SmtpServerConfig {
/// hostname of the SMTP server eg: smtp.gmail.com
pub host: String,
/// portname of the SMTP server eg: 25
pub port: u16,
/// timeout for the SMTP server connection in seconds eg: 10
pub timeout: u64,
/// Username name of the SMTP server
pub username: Option<Secret<String>>,
/// Password of the SMTP server
pub password: Option<Secret<String>>,
/// Connection type of the SMTP server
#[serde(default)]
pub connection: SmtpConnection,
}
/// Enum that contains the connection types of the SMTP server
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SmtpConnection {
#[default]
/// Plaintext connection which MUST then successfully upgrade to TLS via STARTTLS
StartTls,
/// Plaintext connection (very insecure)
Plaintext,
}
impl SmtpServerConfig {
/// Validation for the SMTP server client specific configs
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.host.is_default_or_empty(), || {
Err("email.smtp.host must not be empty")
})?;
self.username.clone().zip(self.password.clone()).map_or(
Ok(()),
|(username, password)| {
when(username.peek().is_default_or_empty(), || {
Err("email.smtp.username must not be empty")
})?;
when(password.peek().is_default_or_empty(), || {
Err("email.smtp.password must not be empty")
})
},
)?;
Ok(())
}
}
#[async_trait::async_trait]
impl EmailClient for SmtpServer {
type RichText = String;
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
Ok(intermediate_string.into_inner())
}
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
_proxy_url: Option<&String>,
) -> EmailResult<()> {
// Create a client every time when the email is being sent
let email_client =
Self::create_client(self).change_context(EmailError::EmailSendingFailure)?;
let email = Message::builder()
.to(Self::to_mail_box(recipient.peek().to_string())?)
.from(Self::to_mail_box(self.sender.clone())?)
.subject(subject)
.header(ContentType::TEXT_HTML)
.body(body)
.map_err(SmtpError::MessageBuildingFailed)
.change_context(EmailError::EmailSendingFailure)?;
email_client
.send(&email)
.map_err(SmtpError::SendingFailure)
.change_context(EmailError::EmailSendingFailure)?;
Ok(())
}
}
/// Errors that could occur during SES operations.
#[derive(Debug, thiserror::Error)]
pub enum SmtpError {
/// An error occurred in the SMTP while sending email.
#[error("Failed to Send Email {0:?}")]
SendingFailure(smtp::Error),
/// An error occurred in the SMTP while building the message content.
#[error("Failed to create connection {0:?}")]
ConnectionFailure(smtp::Error),
/// An error occurred in the SMTP while building the message content.
#[error("Failed to Build Email content {0:?}")]
MessageBuildingFailed(error::Error),
/// An error occurred in the SMTP while building the message content.
#[error("Failed to parse given email {0:?}")]
EmailParsingFailed(AddressError),
}
| 1,442 | 2,325 |
hyperswitch | crates/external_services/src/email/no_email.rs | .rs | use common_utils::{errors::CustomResult, pii};
use router_env::logger;
use crate::email::{EmailClient, EmailError, EmailResult, IntermediateString};
/// Client when email support is disabled
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct NoEmailClient {}
impl NoEmailClient {
/// Constructs a new client when email is disabled
pub async fn create() -> Self {
Self {}
}
}
#[async_trait::async_trait]
impl EmailClient for NoEmailClient {
type RichText = String;
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
Ok(intermediate_string.into_inner())
}
async fn send_email(
&self,
_recipient: pii::Email,
_subject: String,
_body: Self::RichText,
_proxy_url: Option<&String>,
) -> EmailResult<()> {
logger::info!("Email not sent as email support is disabled, please enable any of the supported email clients to send emails");
Ok(())
}
}
| 237 | 2,326 |
hyperswitch | crates/external_services/src/aws_kms/core.rs | .rs | //! Interactions with the AWS KMS SDK
use std::time::Instant;
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::{config::Region, primitives::Blob, Client};
use base64::Engine;
use common_utils::errors::CustomResult;
use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{consts, metrics};
/// Configuration parameters required for constructing a [`AwsKmsClient`].
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[serde(default)]
pub struct AwsKmsConfig {
/// The AWS key identifier of the KMS key used to encrypt or decrypt data.
pub key_id: 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);
}
}
| 1,798 | 2,327 |
hyperswitch | crates/external_services/src/aws_kms/implementers.rs | .rs | //! Trait implementations for aws kms client
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::{
encryption_interface::{EncryptionError, EncryptionManagementInterface},
secrets_interface::{SecretManagementInterface, SecretsManagementError},
};
use masking::{PeekInterface, Secret};
use crate::aws_kms::core::AwsKmsClient;
#[async_trait::async_trait]
impl EncryptionManagementInterface for AwsKmsClient {
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
self.encrypt(input)
.await
.change_context(EncryptionError::EncryptionFailed)
.map(|val| val.into_bytes())
}
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
self.decrypt(input)
.await
.change_context(EncryptionError::DecryptionFailed)
.map(|val| val.into_bytes())
}
}
#[async_trait::async_trait]
impl SecretManagementInterface for AwsKmsClient {
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
self.decrypt(input.peek())
.await
.change_context(SecretsManagementError::FetchSecretFailed)
.map(Into::into)
}
}
| 289 | 2,328 |
hyperswitch | crates/external_services/src/file_storage/aws_s3.rs | .rs | use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{
operation::{
delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError,
},
Client,
};
use aws_sdk_sts::config::Region;
use common_utils::{errors::CustomResult, ext_traits::ConfigExt};
use error_stack::ResultExt;
use super::InvalidFileStorageConfig;
use crate::file_storage::{FileStorageError, FileStorageInterface};
/// Configuration for AWS S3 file storage.
#[derive(Debug, serde::Deserialize, Clone, Default)]
#[serde(default)]
pub struct AwsFileStorageConfig {
/// The AWS region to send file uploads
region: String,
/// The AWS s3 bucket to send file uploads
bucket_name: String,
}
impl AwsFileStorageConfig {
/// Validates the AWS S3 file storage configuration.
pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
use common_utils::fp_utils::when;
when(self.region.is_default_or_empty(), || {
Err(InvalidFileStorageConfig("aws s3 region must not be empty"))
})?;
when(self.bucket_name.is_default_or_empty(), || {
Err(InvalidFileStorageConfig(
"aws s3 bucket name must not be empty",
))
})
}
}
/// AWS S3 file storage client.
#[derive(Debug, Clone)]
pub(super) struct AwsFileStorageClient {
/// AWS S3 client
inner_client: Client,
/// The name of the AWS S3 bucket.
bucket_name: String,
}
impl AwsFileStorageClient {
/// Creates a new AWS S3 file storage client.
pub(super) async fn new(config: &AwsFileStorageConfig) -> Self {
let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
let sdk_config = aws_config::from_env().region(region_provider).load().await;
Self {
inner_client: Client::new(&sdk_config),
bucket_name: config.bucket_name.clone(),
}
}
/// Uploads a file to AWS S3.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), AwsS3StorageError> {
self.inner_client
.put_object()
.bucket(&self.bucket_name)
.key(file_key)
.body(file.into())
.send()
.await
.map_err(AwsS3StorageError::UploadFailure)?;
Ok(())
}
/// Deletes a file from AWS S3.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> {
self.inner_client
.delete_object()
.bucket(&self.bucket_name)
.key(file_key)
.send()
.await
.map_err(AwsS3StorageError::DeleteFailure)?;
Ok(())
}
/// Retrieves a file from AWS S3.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> {
Ok(self
.inner_client
.get_object()
.bucket(&self.bucket_name)
.key(file_key)
.send()
.await
.map_err(AwsS3StorageError::RetrieveFailure)?
.body
.collect()
.await
.map_err(AwsS3StorageError::UnknownError)?
.to_vec())
}
}
#[async_trait::async_trait]
impl FileStorageInterface for AwsFileStorageClient {
/// Uploads a file to AWS S3.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
self.upload_file(file_key, file)
.await
.change_context(FileStorageError::UploadFailed)?;
Ok(())
}
/// Deletes a file from AWS S3.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
self.delete_file(file_key)
.await
.change_context(FileStorageError::DeleteFailed)?;
Ok(())
}
/// Retrieves a file from AWS S3.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
Ok(self
.retrieve_file(file_key)
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
}
/// Enum representing errors that can occur during AWS S3 file storage operations.
#[derive(Debug, thiserror::Error)]
enum AwsS3StorageError {
/// Error indicating that file upload to S3 failed.
#[error("File upload to S3 failed: {0:?}")]
UploadFailure(aws_sdk_s3::error::SdkError<PutObjectError>),
/// Error indicating that file retrieval from S3 failed.
#[error("File retrieve from S3 failed: {0:?}")]
RetrieveFailure(aws_sdk_s3::error::SdkError<GetObjectError>),
/// Error indicating that file deletion from S3 failed.
#[error("File delete from S3 failed: {0:?}")]
DeleteFailure(aws_sdk_s3::error::SdkError<DeleteObjectError>),
/// Unknown error occurred.
#[error("Unknown error occurred: {0:?}")]
UnknownError(aws_sdk_s3::primitives::ByteStreamError),
}
| 1,172 | 2,329 |
hyperswitch | crates/external_services/src/file_storage/file_system.rs | .rs | //! Module for local file system storage operations
use std::{
fs::{remove_file, File},
io::{Read, Write},
path::PathBuf,
};
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use crate::file_storage::{FileStorageError, FileStorageInterface};
/// Constructs the file path for a given file key within the file system.
/// The file path is generated based on the workspace path and the provided file key.
fn get_file_path(file_key: impl AsRef<str>) -> PathBuf {
let mut file_path = PathBuf::new();
file_path.push(std::env::current_dir().unwrap_or(".".into()));
file_path.push("files");
file_path.push(file_key.as_ref());
file_path
}
/// Represents a file system for storing and managing files locally.
#[derive(Debug, Clone)]
pub(super) struct FileSystem;
impl FileSystem {
/// Saves the provided file data to the file system under the specified file key.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileSystemStorageError> {
let file_path = get_file_path(file_key);
// Ignore the file name and create directories in the `file_path` if not exists
std::fs::create_dir_all(
file_path
.parent()
.ok_or(FileSystemStorageError::CreateDirFailed)
.attach_printable("Failed to obtain parent directory")?,
)
.change_context(FileSystemStorageError::CreateDirFailed)?;
let mut file_handler =
File::create(file_path).change_context(FileSystemStorageError::CreateFailure)?;
file_handler
.write_all(&file)
.change_context(FileSystemStorageError::WriteFailure)?;
Ok(())
}
/// Deletes the file associated with the specified file key from the file system.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileSystemStorageError> {
let file_path = get_file_path(file_key);
remove_file(file_path).change_context(FileSystemStorageError::DeleteFailure)?;
Ok(())
}
/// Retrieves the file content associated with the specified file key from the file system.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileSystemStorageError> {
let mut received_data: Vec<u8> = Vec::new();
let file_path = get_file_path(file_key);
let mut file =
File::open(file_path).change_context(FileSystemStorageError::FileOpenFailure)?;
file.read_to_end(&mut received_data)
.change_context(FileSystemStorageError::ReadFailure)?;
Ok(received_data)
}
}
#[async_trait::async_trait]
impl FileStorageInterface for FileSystem {
/// Saves the provided file data to the file system under the specified file key.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
self.upload_file(file_key, file)
.await
.change_context(FileStorageError::UploadFailed)?;
Ok(())
}
/// Deletes the file associated with the specified file key from the file system.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
self.delete_file(file_key)
.await
.change_context(FileStorageError::DeleteFailed)?;
Ok(())
}
/// Retrieves the file content associated with the specified file key from the file system.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
Ok(self
.retrieve_file(file_key)
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
}
/// Represents an error that can occur during local file system storage operations.
#[derive(Debug, thiserror::Error)]
enum FileSystemStorageError {
/// Error indicating opening a file failed
#[error("Failed while opening the file")]
FileOpenFailure,
/// Error indicating file creation failed.
#[error("Failed to create file")]
CreateFailure,
/// Error indicating reading a file failed.
#[error("Failed while reading the file")]
ReadFailure,
/// Error indicating writing to a file failed.
#[error("Failed while writing into file")]
WriteFailure,
/// Error indicating file deletion failed.
#[error("Failed while deleting the file")]
DeleteFailure,
/// Error indicating directory creation failed
#[error("Failed while creating a directory")]
CreateDirFailed,
}
| 974 | 2,330 |
hyperswitch | crates/external_services/src/no_encryption/core.rs | .rs | //! No encryption core functionalities
/// No encryption type
#[derive(Debug, Clone)]
pub struct NoEncryption;
impl NoEncryption {
/// Encryption functionality
pub fn encrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
data.as_ref().into()
}
/// Decryption functionality
pub fn decrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
data.as_ref().into()
}
}
| 102 | 2,331 |
hyperswitch | crates/external_services/src/no_encryption/implementers.rs | .rs | //! Trait implementations for No encryption client
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_interfaces::{
encryption_interface::{EncryptionError, EncryptionManagementInterface},
secrets_interface::{SecretManagementInterface, SecretsManagementError},
};
use masking::{ExposeInterface, Secret};
use crate::no_encryption::core::NoEncryption;
#[async_trait::async_trait]
impl EncryptionManagementInterface for NoEncryption {
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
Ok(self.encrypt(input))
}
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
Ok(self.decrypt(input))
}
}
#[async_trait::async_trait]
impl SecretManagementInterface for NoEncryption {
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
String::from_utf8(self.decrypt(input.expose()))
.map(Into::into)
.change_context(SecretsManagementError::FetchSecretFailed)
.attach_printable("Failed to convert decrypted value to UTF-8")
}
}
| 251 | 2,332 |
hyperswitch | crates/masking/Cargo.toml | .toml | [package]
name = "masking"
description = "Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped."
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
default = ["alloc", "serde", "diesel", "time"]
alloc = ["zeroize/alloc"]
serde = ["dep:serde", "dep:serde_json"]
time = ["dep:time"]
cassandra = ["dep:scylla"]
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
bytes = { version = "1", optional = true }
diesel = { version = "2.2.3", features = ["postgres", "serde_json", "time"], optional = true }
erased-serde = "0.4.4"
serde = { version = "1", features = ["derive"], optional = true }
serde_json = { version = "1.0.115", optional = true }
subtle = "2.5.0"
time = { version = "0.3.35", optional = true, features = ["serde-human-readable"] }
url = { version = "2.5.0", features = ["serde"] }
zeroize = { version = "1.7", default-features = false }
scylla = { git = "https://github.com/juspay/scylla-rust-driver.git",rev = "5700aa2847b25437cdd4fcf34d707aa90dca8b89", optional = true}
[dev-dependencies]
serde_json = "1.0.115"
[lints]
workspace = true
| 423 | 2,333 |
hyperswitch | crates/masking/README.md | .md | # Masking
Personal Identifiable Information protection.
Wrapper types and traits for secret management which help ensure they aren't
accidentally copied, logged, or otherwise exposed (as much as possible), and
also ensure secrets are securely wiped from memory when dropped.
Secret-keeping library inspired by `secrecy`.
This solution has such advantages over alternatives:
- alternatives have not implemented several traits from the box which are needed
- alternatives do not have WeakSecret and Secret differentiation
- alternatives do not support masking strategies
- alternatives had several minor problems
## How to use
To convert a non-secret variable into a secret, use `Secret::new()`:
```rust
use masking::Secret;
let card_number: Secret<String> = Secret::new(String::from("1234 5678 9012 3456"));
assert_eq!(format!("{:?}", card_number), "*** alloc::string::String ***");
```
To get a reference to the inner value from the secret, use `peek()`:
```rust
use masking::{PeekInterface, Secret};
let card_number: Secret<String> = Secret::new(String::from("1234 5678 9012 3456"));
let last4_digits: &str = card_number.peek();
```
To get the owned inner value from the secret, use `expose()`:
```rust
use masking::{ExposeInterface, Secret};
let card_number: Secret<String> = Secret::new(String::from("1234 5678 9012 3456"));
let last4_digits: String = card_number.expose();
```
For fields that are `Option<T>`, you can use `expose_option()`:
```rust
use masking::{ExposeOptionInterface, Secret};
let card_number: Option<Secret<String>> = Some(Secret::new(String::from("1234 5678 9012 3456")));
let card_number_str: String = card_number.expose_option().unwrap_or_default();
assert_eq!(format!("{}", card_number_str), "1234 5678 9012 3456");
let card_number: Option<Secret<String>> = None;
let card_number_str: String = card_number.expose_option().unwrap_or_default();
assert_eq!(format!("{}", card_number_str), "");
```
| 507 | 2,334 |
hyperswitch | crates/masking/tests/basic.rs | .rs | #![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(())
}
| 1,027 | 2,335 |
hyperswitch | crates/masking/src/vec.rs | .rs | //! Secret `Vec` types
//!
//! There is not alias type by design.
#[cfg(feature = "serde")]
use super::{SerializableSecret, Serialize};
#[cfg(feature = "serde")]
impl<S: Serialize> SerializableSecret for Vec<S> {}
| 51 | 2,336 |
hyperswitch | crates/masking/src/boxed.rs | .rs | //! `Box` types containing secrets
//!
//! There is not alias type by design.
#[cfg(feature = "serde")]
use super::{SerializableSecret, Serialize};
#[cfg(feature = "serde")]
impl<S: Serialize> SerializableSecret for Box<S> {}
| 52 | 2,337 |
hyperswitch | crates/masking/src/serde.rs | .rs | //! Serde-related.
pub use erased_serde::Serialize as ErasedSerialize;
pub use serde::{de, Deserialize, Serialize, Serializer};
use serde_json::{value::Serializer as JsonValueSerializer, Value};
use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret};
/// Marker trait for secret types which can be [`Serialize`]-d by [`serde`].
///
/// When the `serde` feature of this crate is enabled and types are marked with
/// this trait, they receive a [`Serialize` impl] for `Secret<T>`.
/// (NOTE: all types which impl `DeserializeOwned` receive a [`Deserialize`]
/// impl)
///
/// This is done deliberately to prevent accidental exfiltration of secrets
/// via `serde` serialization.
#[cfg_attr(docsrs, cfg(feature = "serde"))]
pub trait SerializableSecret: Serialize {}
// #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
// pub trait NonSerializableSecret: Serialize {}
impl SerializableSecret for Value {}
impl SerializableSecret for u8 {}
impl SerializableSecret for u16 {}
impl SerializableSecret for i8 {}
impl SerializableSecret for i32 {}
impl SerializableSecret for i64 {}
impl SerializableSecret for url::Url {}
#[cfg(feature = "time")]
impl SerializableSecret for time::Date {}
impl<'de, T, I> Deserialize<'de> for Secret<T, I>
where
T: Clone + de::DeserializeOwned + Sized,
I: Strategy<T>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
T::deserialize(deserializer).map(Self::new)
}
}
impl<T, I> Serialize for Secret<T, I>
where
T: SerializableSecret + Serialize + Sized,
I: Strategy<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
pii_serializer::pii_serialize(self, serializer)
}
}
impl<'de, T, I> Deserialize<'de> for StrongSecret<T, I>
where
T: Clone + de::DeserializeOwned + Sized + ZeroizableSecret,
I: Strategy<T>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(Self::new)
}
}
impl<T, I> Serialize for StrongSecret<T, I>
where
T: SerializableSecret + Serialize + ZeroizableSecret + Sized,
I: Strategy<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
pii_serializer::pii_serialize(self, serializer)
}
}
/// Masked serialization.
///
/// the default behaviour for secrets is to serialize in exposed format since the common use cases
/// for storing the secret to database or sending it over the network requires the secret to be exposed
/// This method allows to serialize the secret in masked format if needed for logs or other insecure exposures
pub fn masked_serialize<T: Serialize>(value: &T) -> Result<Value, serde_json::Error> {
value.serialize(PIISerializer {
inner: JsonValueSerializer,
})
}
/// Masked serialization.
///
/// Trait object for supporting serialization to Value while accounting for masking
/// The usual Serde Serialize trait cannot be used as trait objects
/// like &dyn Serialize or boxed trait objects like Box<dyn Serialize> because of Rust's "object safety" rules.
/// In particular, the trait contains generic methods which cannot be made into a trait object.
/// In this case we remove the generic for assuming the serialization to be of 2 types only raw json or masked json
pub trait ErasedMaskSerialize: ErasedSerialize {
/// Masked serialization.
fn masked_serialize(&self) -> Result<Value, serde_json::Error>;
}
impl<T: Serialize + ErasedSerialize> ErasedMaskSerialize for T {
fn masked_serialize(&self) -> Result<Value, serde_json::Error> {
masked_serialize(self)
}
}
impl Serialize for dyn ErasedMaskSerialize + '_ {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
erased_serde::serialize(self, serializer)
}
}
impl Serialize for dyn ErasedMaskSerialize + '_ + Send {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
erased_serde::serialize(self, serializer)
}
}
use pii_serializer::PIISerializer;
mod pii_serializer {
use std::fmt::Display;
pub(super) fn pii_serialize<
V: Serialize,
T: std::fmt::Debug + PeekInterface<V>,
S: Serializer,
>(
value: &T,
serializer: S,
) -> Result<S::Ok, S::Error> {
// Mask the value if the serializer is of type PIISerializer
// or send empty map if the serializer is of type FlatMapSerializer over PiiSerializer
if std::any::type_name::<S>() == std::any::type_name::<PIISerializer>() {
format!("{value:?}").serialize(serializer)
} else if std::any::type_name::<S>()
== std::any::type_name::<
serde::__private::ser::FlatMapSerializer<'_, SerializeMap<PIISerializer>>,
>()
{
std::collections::HashMap::<String, String>::from([]).serialize(serializer)
} else {
value.peek().serialize(serializer)
}
}
use serde::{Serialize, Serializer};
use serde_json::{value::Serializer as JsonValueSerializer, Map, Value};
use crate::PeekInterface;
pub(super) struct PIISerializer {
pub inner: JsonValueSerializer,
}
impl Clone for PIISerializer {
fn clone(&self) -> Self {
Self {
inner: JsonValueSerializer,
}
}
}
impl Serializer for PIISerializer {
type Ok = Value;
type Error = serde_json::Error;
type SerializeSeq = SerializeVec<Self>;
type SerializeTuple = SerializeVec<Self>;
type SerializeTupleStruct = SerializeVec<Self>;
type SerializeTupleVariant = SerializeTupleVariant<Self>;
type SerializeMap = SerializeMap<Self>;
type SerializeStruct = SerializeMap<Self>;
type SerializeStructVariant = SerializeStructVariant<Self>;
#[inline]
fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_bool(value)
}
#[inline]
fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(value.into())
}
#[inline]
fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(value.into())
}
#[inline]
fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(value.into())
}
fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_i64(value)
}
fn serialize_i128(self, value: i128) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_i128(value)
}
#[inline]
fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(value.into())
}
#[inline]
fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(value.into())
}
#[inline]
fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(value.into())
}
#[inline]
fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
Ok(Value::Number(value.into()))
}
fn serialize_u128(self, value: u128) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_u128(value)
}
#[inline]
fn serialize_f32(self, float: f32) -> Result<Self::Ok, Self::Error> {
Ok(Value::from(float))
}
#[inline]
fn serialize_f64(self, float: f64) -> Result<Self::Ok, Self::Error> {
Ok(Value::from(float))
}
#[inline]
fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> {
let mut s = String::new();
s.push(value);
Ok(Value::String(s))
}
#[inline]
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
Ok(Value::String(value.to_owned()))
}
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
let vec = value.iter().map(|&b| Value::Number(b.into())).collect();
Ok(Value::Array(vec))
}
#[inline]
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::Null)
}
#[inline]
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
#[inline]
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
self.serialize_str(variant)
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
let mut values = Map::new();
values.insert(String::from(variant), value.serialize(self)?);
Ok(Value::Object(values))
}
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Ok(SerializeVec {
vec: Vec::with_capacity(len.unwrap_or(0)),
ser: self,
})
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Ok(SerializeTupleVariant {
name: String::from(variant),
vec: Vec::with_capacity(len),
ser: self,
})
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Ok(SerializeMap {
inner: self.clone().inner.serialize_map(len)?,
ser: self,
})
}
fn serialize_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
self.serialize_map(Some(len))
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Ok(SerializeStructVariant {
name: String::from(variant),
map: Map::new(),
ser: self,
})
}
fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Display,
{
self.inner.collect_str(value)
}
}
pub(super) struct SerializeVec<T: Serializer> {
vec: Vec<Value>,
ser: T,
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeSeq for SerializeVec<T> {
type Ok = Value;
type Error = T::Error;
fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.vec.push(value.serialize(self.ser.clone())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::Array(self.vec))
}
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTuple for SerializeVec<T> {
type Ok = Value;
type Error = T::Error;
fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
serde::ser::SerializeSeq::end(self)
}
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleStruct for SerializeVec<T> {
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
serde::ser::SerializeSeq::end(self)
}
}
pub(super) struct SerializeStructVariant<T: Serializer> {
name: String,
map: Map<String, Value>,
ser: T,
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeStructVariant
for SerializeStructVariant<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.map
.insert(String::from(key), value.serialize(self.ser.clone())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
let mut object = Map::new();
object.insert(self.name, Value::Object(self.map));
Ok(Value::Object(object))
}
}
pub(super) struct SerializeTupleVariant<T: Serializer> {
name: String,
vec: Vec<Value>,
ser: T,
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleVariant
for SerializeTupleVariant<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.vec.push(value.serialize(self.ser.clone())?);
Ok(())
}
fn end(self) -> Result<Value, Self::Error> {
let mut object = Map::new();
object.insert(self.name, Value::Array(self.vec));
Ok(Value::Object(object))
}
}
pub(super) struct SerializeMap<T: Serializer> {
inner: <serde_json::value::Serializer as Serializer>::SerializeMap,
ser: T,
}
impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeMap
for SerializeMap<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_key<V>(&mut self, key: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.inner.serialize_key(key)?;
Ok(())
}
fn serialize_value<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
let value = value.serialize(self.ser.clone())?;
self.inner.serialize_value(&value)?;
Ok(())
}
fn end(self) -> Result<Value, Self::Error> {
self.inner.end()
}
}
impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeStruct
for SerializeMap<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
serde::ser::SerializeMap::serialize_entry(self, key, value)
}
fn end(self) -> Result<Value, Self::Error> {
serde::ser::SerializeMap::end(self)
}
}
}
| 3,935 | 2,338 |
hyperswitch | crates/masking/src/strong_secret.rs | .rs | //! Structure describing secret.
use std::{fmt, marker::PhantomData};
use subtle::ConstantTimeEq;
use zeroize::{self, Zeroize as ZeroizableSecret};
use crate::{strategy::Strategy, PeekInterface};
/// Secret thing.
///
/// To get access to value use method `expose()` of trait [`crate::ExposeInterface`].
pub struct StrongSecret<Secret: ZeroizableSecret, MaskingStrategy = crate::WithType> {
/// Inner secret value
pub(crate) inner_secret: Secret,
pub(crate) masking_strategy: PhantomData<MaskingStrategy>,
}
impl<Secret: ZeroizableSecret, MaskingStrategy> StrongSecret<Secret, MaskingStrategy> {
/// Take ownership of a secret value
pub fn new(secret: Secret) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> PeekInterface<Secret>
for StrongSecret<Secret, MaskingStrategy>
{
fn peek(&self) -> &Secret {
&self.inner_secret
}
fn peek_mut(&mut self) -> &mut Secret {
&mut self.inner_secret
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> From<Secret>
for StrongSecret<Secret, MaskingStrategy>
{
fn from(secret: Secret) -> Self {
Self::new(secret)
}
}
impl<Secret: Clone + ZeroizableSecret, MaskingStrategy> Clone
for StrongSecret<Secret, MaskingStrategy>
{
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
}
impl<Secret, MaskingStrategy> PartialEq for StrongSecret<Secret, MaskingStrategy>
where
Self: PeekInterface<Secret>,
Secret: ZeroizableSecret + StrongEq,
{
fn eq(&self, other: &Self) -> bool {
StrongEq::strong_eq(self.peek(), other.peek())
}
}
impl<Secret, MaskingStrategy> Eq for StrongSecret<Secret, MaskingStrategy>
where
Self: PeekInterface<Secret>,
Secret: ZeroizableSecret + StrongEq,
{
}
impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Debug
for StrongSecret<Secret, MaskingStrategy>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Display
for StrongSecret<Secret, MaskingStrategy>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> Default for StrongSecret<Secret, MaskingStrategy>
where
Secret: ZeroizableSecret + Default,
{
fn default() -> Self {
Secret::default().into()
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> Drop for StrongSecret<Secret, MaskingStrategy> {
fn drop(&mut self) {
self.inner_secret.zeroize();
}
}
trait StrongEq {
fn strong_eq(&self, other: &Self) -> bool;
}
impl StrongEq for String {
fn strong_eq(&self, other: &Self) -> bool {
let lhs = self.as_bytes();
let rhs = other.as_bytes();
bool::from(lhs.ct_eq(rhs))
}
}
impl StrongEq for Vec<u8> {
fn strong_eq(&self, other: &Self) -> bool {
let lhs = &self;
let rhs = &other;
bool::from(lhs.ct_eq(rhs))
}
}
| 824 | 2,339 |
hyperswitch | crates/masking/src/cassandra.rs | .rs | use scylla::{
deserialize::DeserializeValue,
frame::response::result::ColumnType,
serialize::{
value::SerializeValue,
writers::{CellWriter, WrittenCellProof},
SerializationError,
},
};
use crate::{abs::PeekInterface, StrongSecret};
impl<T> SerializeValue for StrongSecret<T>
where
T: SerializeValue + zeroize::Zeroize + Clone,
{
fn serialize<'b>(
&self,
column_type: &ColumnType<'_>,
writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
self.peek().serialize(column_type, writer)
}
}
impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for StrongSecret<T>
where
T: DeserializeValue<'frame, 'metadata> + zeroize::Zeroize + Clone,
{
fn type_check(column_type: &ColumnType<'_>) -> Result<(), scylla::deserialize::TypeCheckError> {
T::type_check(column_type)
}
fn deserialize(
column_type: &'metadata ColumnType<'metadata>,
v: Option<scylla::deserialize::FrameSlice<'frame>>,
) -> Result<Self, scylla::deserialize::DeserializationError> {
Ok(Self::new(T::deserialize(column_type, v)?))
}
}
| 286 | 2,340 |
hyperswitch | crates/masking/src/abs.rs | .rs | //! Abstract data types.
use crate::Secret;
/// Interface to expose a reference to an inner secret
pub trait PeekInterface<S> {
/// Only method providing access to the secret value.
fn peek(&self) -> &S;
/// Provide a mutable reference to the inner value.
fn peek_mut(&mut self) -> &mut S;
}
/// Interface that consumes a option secret and returns the value.
pub trait ExposeOptionInterface<S> {
/// Expose option.
fn expose_option(self) -> S;
}
/// Interface that consumes a secret and returns the inner value.
pub trait ExposeInterface<S> {
/// Consume the secret and return the inner value
fn expose(self) -> S;
}
impl<S, I> ExposeOptionInterface<Option<S>> for Option<Secret<S, I>>
where
S: Clone,
I: crate::Strategy<S>,
{
fn expose_option(self) -> Option<S> {
self.map(ExposeInterface::expose)
}
}
impl<S, I> ExposeInterface<S> for Secret<S, I>
where
I: crate::Strategy<S>,
{
fn expose(self) -> S {
self.inner_secret
}
}
/// Interface that consumes a secret and converts it to a secret with a different masking strategy.
pub trait SwitchStrategy<FromStrategy, ToStrategy> {
/// The type returned by `switch_strategy()`.
type Output;
/// Consumes the secret and converts it to a secret with a different masking strategy.
fn switch_strategy(self) -> Self::Output;
}
impl<S, FromStrategy, ToStrategy> SwitchStrategy<FromStrategy, ToStrategy>
for Secret<S, FromStrategy>
where
FromStrategy: crate::Strategy<S>,
ToStrategy: crate::Strategy<S>,
{
type Output = Secret<S, ToStrategy>;
fn switch_strategy(self) -> Self::Output {
Secret::new(self.inner_secret)
}
}
| 409 | 2,341 |
hyperswitch | crates/masking/src/maskable.rs | .rs | //! This module contains Masking objects and traits
use crate::{ExposeInterface, Secret};
/// An Enum that allows us to optionally mask data, based on which enum variant that data is stored
/// in.
#[derive(Clone, Eq, PartialEq)]
pub enum Maskable<T: Eq + PartialEq + Clone> {
/// Variant which masks the data by wrapping in a Secret
Masked(Secret<T>),
/// Varant which doesn't mask the data
Normal(T),
}
impl<T: std::fmt::Debug + Clone + Eq + PartialEq> std::fmt::Debug for Maskable<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Masked(secret_value) => std::fmt::Debug::fmt(secret_value, f),
Self::Normal(value) => std::fmt::Debug::fmt(value, f),
}
}
}
impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Self::Masked(value) => crate::PeekInterface::peek(value).hash(state),
Self::Normal(value) => value.hash(state),
}
}
}
impl<T: Eq + PartialEq + Clone> Maskable<T> {
/// Get the inner data while consuming self
pub fn into_inner(self) -> T {
match self {
Self::Masked(inner_secret) => inner_secret.expose(),
Self::Normal(inner) => inner,
}
}
/// Create a new Masked data
pub fn new_masked(item: Secret<T>) -> Self {
Self::Masked(item)
}
/// Create a new non-masked data
pub fn new_normal(item: T) -> Self {
Self::Normal(item)
}
/// Checks whether the data is masked.
/// Returns `true` if the data is wrapped in the `Masked` variant,
/// returns `false` otherwise.
pub fn is_masked(&self) -> bool {
matches!(self, Self::Masked(_))
}
/// Checks whether the data is normal (not masked).
/// Returns `true` if the data is wrapped in the `Normal` variant,
/// returns `false` otherwise.
pub fn is_normal(&self) -> bool {
matches!(self, Self::Normal(_))
}
}
/// Trait for providing a method on custom types for constructing `Maskable`
pub trait Mask {
/// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone`
type Output: Eq + Clone + PartialEq;
/// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self`
fn into_masked(self) -> Maskable<Self::Output>;
}
impl Mask for String {
type Output = Self;
fn into_masked(self) -> Maskable<Self::Output> {
Maskable::new_masked(self.into())
}
}
impl Mask for Secret<String> {
type Output = String;
fn into_masked(self) -> Maskable<Self::Output> {
Maskable::new_masked(self)
}
}
impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> {
fn from(value: T) -> Self {
Self::new_normal(value)
}
}
impl From<&str> for Maskable<String> {
fn from(value: &str) -> Self {
Self::new_normal(value.to_string())
}
}
| 779 | 2,342 |
hyperswitch | crates/masking/src/string.rs | .rs | //! Secret strings
//!
//! There is not alias type by design.
use alloc::{
str::FromStr,
string::{String, ToString},
};
#[cfg(feature = "serde")]
use super::SerializableSecret;
use super::{Secret, Strategy};
use crate::StrongSecret;
#[cfg(feature = "serde")]
impl SerializableSecret for String {}
impl<I> FromStr for Secret<String, I>
where
I: Strategy<String>,
{
type Err = core::convert::Infallible;
fn from_str(src: &str) -> Result<Self, Self::Err> {
Ok(Self::new(src.to_string()))
}
}
impl<I> FromStr for StrongSecret<String, I>
where
I: Strategy<String>,
{
type Err = core::convert::Infallible;
fn from_str(src: &str) -> Result<Self, Self::Err> {
Ok(Self::new(src.to_string()))
}
}
| 195 | 2,343 |
hyperswitch | crates/masking/src/lib.rs | .rs | #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
#![warn(missing_docs)]
//! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped.
//! Secret-keeping library inspired by secrecy.
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
pub use zeroize::{self, DefaultIsZeroes, Zeroize as ZeroizableSecret};
mod strategy;
pub use strategy::{Strategy, WithType, WithoutType};
mod abs;
pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrategy};
mod secret;
mod strong_secret;
pub use secret::Secret;
pub use strong_secret::StrongSecret;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
mod boxed;
#[cfg(feature = "bytes")]
mod bytes;
#[cfg(feature = "bytes")]
pub use self::bytes::SecretBytesMut;
#[cfg(feature = "alloc")]
mod string;
#[cfg(feature = "alloc")]
mod vec;
#[cfg(feature = "serde")]
mod serde;
#[cfg(feature = "serde")]
pub use crate::serde::{
masked_serialize, Deserialize, ErasedMaskSerialize, SerializableSecret, Serialize,
};
/// This module should be included with asterisk.
///
/// `use masking::prelude::*;`
pub mod prelude {
pub use super::{ExposeInterface, ExposeOptionInterface, PeekInterface};
}
#[cfg(feature = "diesel")]
mod diesel;
#[cfg(feature = "cassandra")]
mod cassandra;
pub mod maskable;
pub use maskable::*;
| 372 | 2,344 |
hyperswitch | crates/masking/src/secret.rs | .rs | //! Structure describing secret.
use std::{fmt, marker::PhantomData};
use crate::{strategy::Strategy, PeekInterface, StrongSecret};
/// Secret thing.
///
/// To get access to value use method `expose()` of trait [`crate::ExposeInterface`].
///
/// ## Masking
/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a zero-variant
/// enum and pass this enum as a second generic parameter to [`Secret`] while defining it.
/// [`Secret`] will take care of applying the masking strategy on the inner secret when being
/// displayed.
///
/// ## Masking Example
///
/// ```
/// use masking::Strategy;
/// use masking::Secret;
/// use std::fmt;
///
/// enum MyStrategy {}
///
/// impl<T> Strategy<T> for MyStrategy
/// where
/// T: fmt::Display
/// {
/// fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "{}", val.to_string().to_ascii_lowercase())
/// }
/// }
///
/// let my_secret: Secret<String, MyStrategy> = Secret::new("HELLO".to_string());
///
/// assert_eq!("hello", &format!("{:?}", my_secret));
/// ```
pub struct Secret<Secret, MaskingStrategy = crate::WithType>
where
MaskingStrategy: Strategy<Secret>,
{
pub(crate) inner_secret: Secret,
pub(crate) masking_strategy: PhantomData<MaskingStrategy>,
}
impl<SecretValue, MaskingStrategy> Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
/// Take ownership of a secret value
pub fn new(secret: SecretValue) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
/// Zip 2 secrets with the same masking strategy into one
pub fn zip<OtherSecretValue>(
self,
other: Secret<OtherSecretValue, MaskingStrategy>,
) -> Secret<(SecretValue, OtherSecretValue), MaskingStrategy>
where
MaskingStrategy: Strategy<OtherSecretValue> + Strategy<(SecretValue, OtherSecretValue)>,
{
(self.inner_secret, other.inner_secret).into()
}
/// consume self and modify the inner value
pub fn map<OtherSecretValue>(
self,
f: impl FnOnce(SecretValue) -> OtherSecretValue,
) -> Secret<OtherSecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<OtherSecretValue>,
{
f(self.inner_secret).into()
}
/// Convert to [`StrongSecret`]
pub fn into_strong(self) -> StrongSecret<SecretValue, MaskingStrategy>
where
SecretValue: zeroize::DefaultIsZeroes,
{
StrongSecret::new(self.inner_secret)
}
}
impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue>
for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn peek(&self) -> &SecretValue {
&self.inner_secret
}
fn peek_mut(&mut self) -> &mut SecretValue {
&mut self.inner_secret
}
}
impl<SecretValue, MaskingStrategy> From<SecretValue> for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn from(secret: SecretValue) -> Self {
Self::new(secret)
}
}
impl<SecretValue, MaskingStrategy> Clone for Secret<SecretValue, MaskingStrategy>
where
SecretValue: Clone,
MaskingStrategy: Strategy<SecretValue>,
{
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
}
impl<SecretValue, MaskingStrategy> PartialEq for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: PartialEq,
MaskingStrategy: Strategy<SecretValue>,
{
fn eq(&self, other: &Self) -> bool {
self.peek().eq(other.peek())
}
}
impl<SecretValue, MaskingStrategy> Eq for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: Eq,
MaskingStrategy: Strategy<SecretValue>,
{
}
impl<SecretValue, MaskingStrategy> fmt::Debug for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<SecretValue, MaskingStrategy> Default for Secret<SecretValue, MaskingStrategy>
where
SecretValue: Default,
MaskingStrategy: Strategy<SecretValue>,
{
fn default() -> Self {
SecretValue::default().into()
}
}
// Required by base64-serde to serialize Secret of Vec<u8> which contains the base64 decoded value
impl AsRef<[u8]> for Secret<Vec<u8>> {
fn as_ref(&self) -> &[u8] {
self.peek().as_slice()
}
}
| 1,143 | 2,345 |
hyperswitch | crates/masking/src/bytes.rs | .rs | //! 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)
}
}
| 711 | 2,346 |
hyperswitch | crates/masking/src/diesel.rs | .rs | //! Diesel-related.
use diesel::{
backend::Backend,
deserialize::{self, FromSql, Queryable},
expression::AsExpression,
internal::derives::as_expression::Bound,
serialize::{self, Output, ToSql},
sql_types,
};
use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret};
impl<S, I, T> AsExpression<T> for &Secret<S, I>
where
T: sql_types::SingleValue,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, T> AsExpression<T> for &&Secret<S, I>
where
T: sql_types::SingleValue,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, T, DB> ToSql<T, DB> for Secret<S, I>
where
DB: Backend,
S: ToSql<T, DB>,
I: Strategy<S>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
ToSql::<T, DB>::to_sql(&self.inner_secret, out)
}
}
impl<DB, S, T, I> FromSql<T, DB> for Secret<S, I>
where
DB: Backend,
S: FromSql<T, DB>,
I: Strategy<S>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
S::from_sql(bytes).map(|raw| raw.into())
}
}
impl<S, I, T> AsExpression<T> for Secret<S, I>
where
T: sql_types::SingleValue,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<ST, DB, S, I> Queryable<ST, DB> for Secret<S, I>
where
DB: Backend,
I: Strategy<S>,
ST: sql_types::SingleValue,
Self: FromSql<ST, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<S, I, T> AsExpression<T> for &StrongSecret<S, I>
where
T: sql_types::SingleValue,
S: ZeroizableSecret,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, T> AsExpression<T> for &&StrongSecret<S, I>
where
T: sql_types::SingleValue,
S: ZeroizableSecret,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, DB, T> ToSql<T, DB> for StrongSecret<S, I>
where
DB: Backend,
S: ToSql<T, DB> + ZeroizableSecret,
I: Strategy<S>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
ToSql::<T, DB>::to_sql(&self.inner_secret, out)
}
}
impl<DB, S, I, T> FromSql<T, DB> for StrongSecret<S, I>
where
DB: Backend,
S: FromSql<T, DB> + ZeroizableSecret,
I: Strategy<S>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
S::from_sql(bytes).map(|raw| raw.into())
}
}
impl<S, I, T> AsExpression<T> for StrongSecret<S, I>
where
T: sql_types::SingleValue,
S: ZeroizableSecret,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<ST, DB, S, I> Queryable<ST, DB> for StrongSecret<S, I>
where
I: Strategy<S>,
DB: Backend,
S: ZeroizableSecret,
ST: sql_types::SingleValue,
Self: FromSql<ST, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
| 1,019 | 2,347 |
hyperswitch | crates/masking/src/strategy.rs | .rs | use core::fmt;
/// Debugging trait which is specialized for handling secret values
pub trait Strategy<T> {
/// Format information about the secret's type.
fn fmt(value: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
}
/// Debug with type
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WithType {}
impl<T> Strategy<T> for WithType {
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ")?;
fmt.write_str(std::any::type_name::<T>())?;
fmt.write_str(" ***")
}
}
/// Debug without type
pub enum WithoutType {}
impl<T> Strategy<T> for WithoutType {
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ***")
}
}
| 206 | 2,348 |
hyperswitch | crates/hyperswitch_constraint_graph/Cargo.toml | .toml | [package]
name = "hyperswitch_constraint_graph"
description = "Constraint Graph Framework for modeling Domain-Specific Constraints"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[features]
viz = ["dep:graphviz-rust"]
[dependencies]
erased-serde = "0.3.28"
graphviz-rust = { version = "0.6.2", optional = true }
rustc-hash = "1.1.0"
serde = { version = "1.0.163", features = ["derive", "rc"] }
strum = { version = "0.25", features = ["derive"] }
thiserror = "1.0.43"
[lints]
workspace = true
| 164 | 2,349 |
hyperswitch | crates/hyperswitch_constraint_graph/src/graph.rs | .rs | use std::sync::{Arc, Weak};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
builder,
dense_map::DenseMap,
error::{self, AnalysisTrace, GraphError},
types::{
CheckingContext, CycleCheck, DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId,
Memoization, Metadata, Node, NodeId, NodeType, NodeValue, Relation, RelationResolution,
Strength, ValueNode,
},
};
#[derive(Debug)]
struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> {
ctx: &'a C,
node: &'a Node<V>,
node_id: NodeId,
relation: Relation,
strength: Strength,
memo: &'a mut Memoization<V>,
cycle_map: &'a mut CycleCheck,
domains: Option<&'a [DomainId]>,
}
#[derive(Debug)]
pub struct ConstraintGraph<V: ValueNode> {
pub domain: DenseMap<DomainId, DomainInfo>,
pub domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>,
pub nodes: DenseMap<NodeId, Node<V>>,
pub edges: DenseMap<EdgeId, Edge>,
pub value_map: FxHashMap<NodeValue<V>, NodeId>,
pub node_info: DenseMap<NodeId, Option<&'static str>>,
pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>,
}
impl<V> ConstraintGraph<V>
where
V: ValueNode,
{
fn get_predecessor_edges_by_domain(
&self,
node_id: NodeId,
domains: Option<&[DomainId]>,
) -> Result<Vec<&Edge>, GraphError<V>> {
let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?;
let mut final_list = Vec::new();
for &pred in &node.preds {
let edge = self.edges.get(pred).ok_or(GraphError::EdgeNotFound)?;
if let Some((domain_id, domains)) = edge.domain.zip(domains) {
if domains.contains(&domain_id) {
final_list.push(edge);
}
} else if edge.domain.is_none() {
final_list.push(edge);
}
}
Ok(final_list)
}
#[allow(clippy::too_many_arguments)]
pub fn check_node<C>(
&self,
ctx: &C,
node_id: NodeId,
relation: Relation,
strength: Strength,
memo: &mut Memoization<V>,
cycle_map: &mut CycleCheck,
domains: Option<&[String]>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let domains = domains
.map(|domain_idents| {
domain_idents
.iter()
.map(|domain_ident| {
self.domain_identifier_map
.get(&DomainIdentifier::new(domain_ident.to_string()))
.copied()
.ok_or(GraphError::DomainNotFound)
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
self.check_node_inner(
ctx,
node_id,
relation,
strength,
memo,
cycle_map,
domains.as_deref(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn check_node_inner<C>(
&self,
ctx: &C,
node_id: NodeId,
relation: Relation,
strength: Strength,
memo: &mut Memoization<V>,
cycle_map: &mut CycleCheck,
domains: Option<&[DomainId]>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?;
if let Some(already_memo) = memo.get(&(node_id, relation, strength)) {
already_memo
.clone()
.map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err)))
} else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).copied()
{
let strength_relation = Strength::get_resolved_strength(initial_strength, strength);
let relation_resolve =
RelationResolution::get_resolved_relation(initial_relation, relation.into());
cycle_map.entry(node_id).and_modify(|value| {
value.0 = strength_relation;
value.1 = relation_resolve
});
Ok(())
} else {
let check_node_context = CheckNodeContext {
node,
node_id,
relation,
strength,
memo,
cycle_map,
ctx,
domains,
};
match &node.node_type {
NodeType::AllAggregator => self.validate_all_aggregator(check_node_context),
NodeType::AnyAggregator => self.validate_any_aggregator(check_node_context),
NodeType::InAggregator(expected) => {
self.validate_in_aggregator(check_node_context, expected)
}
NodeType::Value(val) => self.validate_value_node(check_node_context, val),
}
}
}
fn validate_all_aggregator<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new();
for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? {
vald.cycle_map
.insert(vald.node_id, (vald.strength, vald.relation.into()));
if let Err(e) = self.check_node_inner(
vald.ctx,
edge.pred,
edge.relation,
edge.strength,
vald.memo,
vald.cycle_map,
vald.domains,
) {
unsatisfied.push(e.get_analysis_trace()?);
}
if let Some((_resolved_strength, resolved_relation)) =
vald.cycle_map.remove(&vald.node_id)
{
if resolved_relation == RelationResolution::Contradiction {
let err = Arc::new(AnalysisTrace::Contradiction {
relation: resolved_relation,
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
return Err(GraphError::AnalysisError(Arc::downgrade(&err)));
}
}
}
if !unsatisfied.is_empty() {
let err = Arc::new(AnalysisTrace::AllAggregation {
unsatisfied,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
} else {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
}
}
fn validate_any_aggregator<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new();
let mut matched_one = false;
for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? {
vald.cycle_map
.insert(vald.node_id, (vald.strength, vald.relation.into()));
if let Err(e) = self.check_node_inner(
vald.ctx,
edge.pred,
edge.relation,
edge.strength,
vald.memo,
vald.cycle_map,
vald.domains,
) {
unsatisfied.push(e.get_analysis_trace()?);
} else {
matched_one = true;
}
if let Some((_resolved_strength, resolved_relation)) =
vald.cycle_map.remove(&vald.node_id)
{
if resolved_relation == RelationResolution::Contradiction {
let err = Arc::new(AnalysisTrace::Contradiction {
relation: resolved_relation,
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
return Err(GraphError::AnalysisError(Arc::downgrade(&err)));
}
}
}
if matched_one || vald.node.preds.is_empty() {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
} else {
let err = Arc::new(AnalysisTrace::AnyAggregation {
unsatisfied: unsatisfied.clone(),
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
}
}
fn validate_in_aggregator<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
expected: &FxHashSet<V>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let the_key = expected
.iter()
.next()
.ok_or_else(|| GraphError::MalformedGraph {
reason: "An OnlyIn aggregator node must have at least one expected value"
.to_string(),
})?
.get_key();
let ctx_vals = if let Some(vals) = vald.ctx.get_values_by_key(&the_key) {
vals
} else {
return if let Strength::Weak = vald.strength {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
} else {
let err = Arc::new(AnalysisTrace::InAggregation {
expected: expected.iter().cloned().collect(),
found: None,
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
};
};
let relation_bool: bool = vald.relation.into();
for ctx_value in ctx_vals {
if expected.contains(&ctx_value) != relation_bool {
let err = Arc::new(AnalysisTrace::InAggregation {
expected: expected.iter().cloned().collect(),
found: Some(ctx_value.clone()),
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))?;
}
}
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
}
fn validate_value_node<C>(
&self,
vald: CheckNodeContext<'_, V, C>,
val: &NodeValue<V>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let mut errors = Vec::<Weak<AnalysisTrace<V>>>::new();
let mut matched_one = false;
self.context_analysis(
vald.node_id,
vald.relation,
vald.strength,
vald.ctx,
val,
vald.memo,
)?;
for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? {
vald.cycle_map
.insert(vald.node_id, (vald.strength, vald.relation.into()));
let result = self.check_node_inner(
vald.ctx,
edge.pred,
edge.relation,
edge.strength,
vald.memo,
vald.cycle_map,
vald.domains,
);
if let Some((resolved_strength, resolved_relation)) =
vald.cycle_map.remove(&vald.node_id)
{
if resolved_relation == RelationResolution::Contradiction {
let err = Arc::new(AnalysisTrace::Contradiction {
relation: resolved_relation,
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
return Err(GraphError::AnalysisError(Arc::downgrade(&err)));
} else if resolved_strength != vald.strength {
self.context_analysis(
vald.node_id,
vald.relation,
resolved_strength,
vald.ctx,
val,
vald.memo,
)?
}
}
match (edge.strength, result) {
(Strength::Strong, Err(trace)) => {
let err = Arc::new(AnalysisTrace::Value {
value: val.clone(),
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new(
trace.get_analysis_trace()?,
))),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))?;
}
(Strength::Strong, Ok(_)) => {
matched_one = true;
}
(Strength::Normal | Strength::Weak, Err(trace)) => {
errors.push(trace.get_analysis_trace()?);
}
(Strength::Normal | Strength::Weak, Ok(_)) => {
matched_one = true;
}
}
}
if matched_one || vald.node.preds.is_empty() {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
Ok(())
} else {
let err = Arc::new(AnalysisTrace::Value {
value: val.clone(),
relation: vald.relation,
info: self.node_info.get(vald.node_id).copied().flatten(),
metadata: self.node_metadata.get(vald.node_id).cloned().flatten(),
predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())),
});
vald.memo.insert(
(vald.node_id, vald.relation, vald.strength),
Err(Arc::clone(&err)),
);
Err(GraphError::AnalysisError(Arc::downgrade(&err)))
}
}
fn context_analysis<C>(
&self,
node_id: NodeId,
relation: Relation,
strength: Strength,
ctx: &C,
val: &NodeValue<V>,
memo: &mut Memoization<V>,
) -> Result<(), GraphError<V>>
where
C: CheckingContext<Value = V>,
{
let in_context = ctx.check_presence(val, strength);
let relation_bool: bool = relation.into();
if in_context != relation_bool {
let err = Arc::new(AnalysisTrace::Value {
value: val.clone(),
relation,
predecessors: None,
info: self.node_info.get(node_id).copied().flatten(),
metadata: self.node_metadata.get(node_id).cloned().flatten(),
});
memo.insert((node_id, relation, strength), Err(Arc::clone(&err)));
Err(GraphError::AnalysisError(Arc::downgrade(&err)))?;
}
if !relation_bool {
memo.insert((node_id, relation, strength), Ok(()));
return Ok(());
}
Ok(())
}
pub fn combine(g1: &Self, g2: &Self) -> Result<Self, GraphError<V>> {
let mut node_builder = builder::ConstraintGraphBuilder::new();
let mut g1_old2new_id = DenseMap::<NodeId, NodeId>::new();
let mut g2_old2new_id = DenseMap::<NodeId, NodeId>::new();
let mut g1_old2new_domain_id = DenseMap::<DomainId, DomainId>::new();
let mut g2_old2new_domain_id = DenseMap::<DomainId, DomainId>::new();
let add_domain = |node_builder: &mut builder::ConstraintGraphBuilder<V>,
domain: DomainInfo|
-> Result<DomainId, GraphError<V>> {
node_builder.make_domain(
domain.domain_identifier.into_inner(),
&domain.domain_description,
)
};
let add_node = |node_builder: &mut builder::ConstraintGraphBuilder<V>,
node: &Node<V>|
-> Result<NodeId, GraphError<V>> {
match &node.node_type {
NodeType::Value(node_value) => {
Ok(node_builder.make_value_node(node_value.clone(), None, None::<()>))
}
NodeType::AllAggregator => {
Ok(node_builder.make_all_aggregator(&[], None, None::<()>, None)?)
}
NodeType::AnyAggregator => {
Ok(node_builder.make_any_aggregator(&[], None, None::<()>, None)?)
}
NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator(
expected.iter().cloned().collect(),
None,
None::<()>,
)?),
}
};
for (_old_domain_id, domain) in g1.domain.iter() {
let new_domain_id = add_domain(&mut node_builder, domain.clone())?;
g1_old2new_domain_id.push(new_domain_id);
}
for (_old_domain_id, domain) in g2.domain.iter() {
let new_domain_id = add_domain(&mut node_builder, domain.clone())?;
g2_old2new_domain_id.push(new_domain_id);
}
for (_old_node_id, node) in g1.nodes.iter() {
let new_node_id = add_node(&mut node_builder, node)?;
g1_old2new_id.push(new_node_id);
}
for (_old_node_id, node) in g2.nodes.iter() {
let new_node_id = add_node(&mut node_builder, node)?;
g2_old2new_id.push(new_node_id);
}
for edge in g1.edges.values() {
let new_pred_id = g1_old2new_id
.get(edge.pred)
.ok_or(GraphError::NodeNotFound)?;
let new_succ_id = g1_old2new_id
.get(edge.succ)
.ok_or(GraphError::NodeNotFound)?;
let domain_ident = edge
.domain
.map(|domain_id| g1.domain.get(domain_id).ok_or(GraphError::DomainNotFound))
.transpose()?
.map(|domain| domain.domain_identifier.clone());
node_builder.make_edge(
*new_pred_id,
*new_succ_id,
edge.strength,
edge.relation,
domain_ident,
)?;
}
for edge in g2.edges.values() {
let new_pred_id = g2_old2new_id
.get(edge.pred)
.ok_or(GraphError::NodeNotFound)?;
let new_succ_id = g2_old2new_id
.get(edge.succ)
.ok_or(GraphError::NodeNotFound)?;
let domain_ident = edge
.domain
.map(|domain_id| g2.domain.get(domain_id).ok_or(GraphError::DomainNotFound))
.transpose()?
.map(|domain| domain.domain_identifier.clone());
node_builder.make_edge(
*new_pred_id,
*new_succ_id,
edge.strength,
edge.relation,
domain_ident,
)?;
}
Ok(node_builder.build())
}
}
#[cfg(feature = "viz")]
mod viz {
use graphviz_rust::{
dot_generator::*,
dot_structures::*,
printer::{DotPrinter, PrinterContext},
};
use crate::{dense_map::EntityId, types, ConstraintGraph, NodeViz, ValueNode};
fn get_node_id(node_id: types::NodeId) -> String {
format!("N{}", node_id.get_id())
}
impl<V> ConstraintGraph<V>
where
V: ValueNode + NodeViz,
<V as ValueNode>::Key: NodeViz,
{
fn get_node_label(node: &types::Node<V>) -> String {
let label = match &node.node_type {
types::NodeType::Value(types::NodeValue::Key(key)) => format!("any {}", key.viz()),
types::NodeType::Value(types::NodeValue::Value(val)) => {
format!("{} = {}", val.get_key().viz(), val.viz())
}
types::NodeType::AllAggregator => "&&".to_string(),
types::NodeType::AnyAggregator => "| |".to_string(),
types::NodeType::InAggregator(agg) => {
let key = if let Some(val) = agg.iter().next() {
val.get_key().viz()
} else {
return "empty in".to_string();
};
let nodes = agg.iter().map(NodeViz::viz).collect::<Vec<_>>();
format!("{key} in [{}]", nodes.join(", "))
}
};
format!("\"{label}\"")
}
fn build_node(cg_node_id: types::NodeId, cg_node: &types::Node<V>) -> Node {
let viz_node_id = get_node_id(cg_node_id);
let viz_node_label = Self::get_node_label(cg_node);
node!(viz_node_id; attr!("label", viz_node_label))
}
fn build_edge(cg_edge: &types::Edge) -> Edge {
let pred_vertex = get_node_id(cg_edge.pred);
let succ_vertex = get_node_id(cg_edge.succ);
let arrowhead = match cg_edge.strength {
types::Strength::Weak => "onormal",
types::Strength::Normal => "normal",
types::Strength::Strong => "normalnormal",
};
let color = match cg_edge.relation {
types::Relation::Positive => "blue",
types::Relation::Negative => "red",
};
edge!(
node_id!(pred_vertex) => node_id!(succ_vertex);
attr!("arrowhead", arrowhead),
attr!("color", color)
)
}
pub fn get_viz_digraph(&self) -> Graph {
graph!(
strict di id!("constraint_graph"),
self.nodes
.iter()
.map(|(node_id, node)| Self::build_node(node_id, node))
.map(Stmt::Node)
.chain(self.edges.values().map(Self::build_edge).map(Stmt::Edge))
.collect::<Vec<_>>()
)
}
pub fn get_viz_digraph_string(&self) -> String {
let mut ctx = PrinterContext::default();
let digraph = self.get_viz_digraph();
digraph.print(&mut ctx)
}
}
}
| 5,106 | 2,350 |
hyperswitch | crates/hyperswitch_constraint_graph/src/types.rs | .rs | use std::{
any::Any,
fmt, hash,
ops::{Deref, DerefMut},
sync::Arc,
};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{dense_map::impl_entity, error::AnalysisTrace};
pub trait KeyNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq {}
pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq {
type Key: KeyNode;
fn get_key(&self) -> Self::Key;
}
#[cfg(feature = "viz")]
pub trait NodeViz {
fn viz(&self) -> String;
}
#[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct NodeId(usize);
impl_entity!(NodeId);
#[derive(Debug)]
pub struct Node<V: ValueNode> {
pub node_type: NodeType<V>,
pub preds: Vec<EdgeId>,
pub succs: Vec<EdgeId>,
}
impl<V: ValueNode> Node<V> {
pub(crate) fn new(node_type: NodeType<V>) -> Self {
Self {
node_type,
preds: Vec::new(),
succs: Vec::new(),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum NodeType<V: ValueNode> {
AllAggregator,
AnyAggregator,
InAggregator(FxHashSet<V>),
Value(NodeValue<V>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum NodeValue<V: ValueNode> {
Key(<V as ValueNode>::Key),
Value(V),
}
impl<V: ValueNode> From<V> for NodeValue<V> {
fn from(value: V) -> Self {
Self::Value(value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EdgeId(usize);
impl_entity!(EdgeId);
#[derive(
Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash, strum::Display, PartialOrd, Ord,
)]
pub enum Strength {
Weak,
Normal,
Strong,
}
impl Strength {
pub fn get_resolved_strength(prev_strength: Self, curr_strength: Self) -> Self {
std::cmp::max(prev_strength, curr_strength)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Relation {
Positive,
Negative,
}
impl From<Relation> for bool {
fn from(value: Relation) -> Self {
matches!(value, Relation::Positive)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)]
pub enum RelationResolution {
Positive,
Negative,
Contradiction,
}
impl From<Relation> for RelationResolution {
fn from(value: Relation) -> Self {
match value {
Relation::Positive => Self::Positive,
Relation::Negative => Self::Negative,
}
}
}
impl RelationResolution {
pub fn get_resolved_relation(prev_relation: Self, curr_relation: Self) -> Self {
if prev_relation != curr_relation {
Self::Contradiction
} else {
curr_relation
}
}
}
#[derive(Debug, Clone)]
pub struct Edge {
pub strength: Strength,
pub relation: Relation,
pub pred: NodeId,
pub succ: NodeId,
pub domain: Option<DomainId>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DomainId(usize);
impl_entity!(DomainId);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DomainIdentifier(String);
impl DomainIdentifier {
pub fn new(identifier: String) -> Self {
Self(identifier)
}
pub fn into_inner(&self) -> String {
self.0.clone()
}
}
impl From<String> for DomainIdentifier {
fn from(value: String) -> Self {
Self(value)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DomainInfo {
pub domain_identifier: DomainIdentifier,
pub domain_description: String,
}
pub trait CheckingContext {
type Value: ValueNode;
fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self
where
L: Into<Self::Value>;
fn check_presence(&self, value: &NodeValue<Self::Value>, strength: Strength) -> bool;
fn get_values_by_key(
&self,
expected: &<Self::Value as ValueNode>::Key,
) -> Option<Vec<Self::Value>>;
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Memoization<V: ValueNode>(
#[allow(clippy::type_complexity)]
FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>,
);
impl<V: ValueNode> Memoization<V> {
pub fn new() -> Self {
Self(FxHashMap::default())
}
}
impl<V: ValueNode> Default for Memoization<V> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<V: ValueNode> Deref for Memoization<V> {
type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<V: ValueNode> DerefMut for Memoization<V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug, Clone)]
pub struct CycleCheck(FxHashMap<NodeId, (Strength, RelationResolution)>);
impl CycleCheck {
pub fn new() -> Self {
Self(FxHashMap::default())
}
}
impl Default for CycleCheck {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Deref for CycleCheck {
type Target = FxHashMap<NodeId, (Strength, RelationResolution)>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for CycleCheck {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub trait Metadata: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {}
erased_serde::serialize_trait_object!(Metadata);
impl<M> Metadata for M where M: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {}
| 1,439 | 2,351 |
hyperswitch | crates/hyperswitch_constraint_graph/src/builder.rs | .rs | use std::sync::Arc;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
dense_map::DenseMap,
error::GraphError,
graph::ConstraintGraph,
types::{
DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Metadata, Node, NodeId, NodeType,
NodeValue, Relation, Strength, ValueNode,
},
};
pub enum DomainIdOrIdentifier {
DomainId(DomainId),
DomainIdentifier(DomainIdentifier),
}
impl From<String> for DomainIdOrIdentifier {
fn from(value: String) -> Self {
Self::DomainIdentifier(DomainIdentifier::new(value))
}
}
impl From<DomainIdentifier> for DomainIdOrIdentifier {
fn from(value: DomainIdentifier) -> Self {
Self::DomainIdentifier(value)
}
}
impl From<DomainId> for DomainIdOrIdentifier {
fn from(value: DomainId) -> Self {
Self::DomainId(value)
}
}
#[derive(Debug)]
pub struct ConstraintGraphBuilder<V: ValueNode> {
domain: DenseMap<DomainId, DomainInfo>,
nodes: DenseMap<NodeId, Node<V>>,
edges: DenseMap<EdgeId, Edge>,
domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>,
value_map: FxHashMap<NodeValue<V>, NodeId>,
edges_map: FxHashMap<(NodeId, NodeId, Option<DomainId>), EdgeId>,
node_info: DenseMap<NodeId, Option<&'static str>>,
node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>,
}
#[allow(clippy::new_without_default)]
impl<V> ConstraintGraphBuilder<V>
where
V: ValueNode,
{
pub fn new() -> Self {
Self {
domain: DenseMap::new(),
nodes: DenseMap::new(),
edges: DenseMap::new(),
domain_identifier_map: FxHashMap::default(),
value_map: FxHashMap::default(),
edges_map: FxHashMap::default(),
node_info: DenseMap::new(),
node_metadata: DenseMap::new(),
}
}
pub fn build(self) -> ConstraintGraph<V> {
ConstraintGraph {
domain: self.domain,
domain_identifier_map: self.domain_identifier_map,
nodes: self.nodes,
edges: self.edges,
value_map: self.value_map,
node_info: self.node_info,
node_metadata: self.node_metadata,
}
}
fn retrieve_domain_from_identifier(
&self,
domain_ident: DomainIdentifier,
) -> Result<DomainId, GraphError<V>> {
self.domain_identifier_map
.get(&domain_ident)
.copied()
.ok_or(GraphError::DomainNotFound)
}
pub fn make_domain(
&mut self,
domain_identifier: String,
domain_description: &str,
) -> Result<DomainId, GraphError<V>> {
let domain_identifier = DomainIdentifier::new(domain_identifier);
Ok(self
.domain_identifier_map
.clone()
.get(&domain_identifier)
.map_or_else(
|| {
let domain_id = self.domain.push(DomainInfo {
domain_identifier: domain_identifier.clone(),
domain_description: domain_description.to_string(),
});
self.domain_identifier_map
.insert(domain_identifier, domain_id);
domain_id
},
|domain_id| *domain_id,
))
}
pub fn make_value_node<M: Metadata>(
&mut self,
value: NodeValue<V>,
info: Option<&'static str>,
metadata: Option<M>,
) -> NodeId {
self.value_map.get(&value).copied().unwrap_or_else(|| {
let node_id = self.nodes.push(Node::new(NodeType::Value(value.clone())));
let _node_info_id = self.node_info.push(info);
let _node_metadata_id = self
.node_metadata
.push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));
self.value_map.insert(value, node_id);
node_id
})
}
pub fn make_edge<T: Into<DomainIdOrIdentifier>>(
&mut self,
pred_id: NodeId,
succ_id: NodeId,
strength: Strength,
relation: Relation,
domain: Option<T>,
) -> Result<EdgeId, GraphError<V>> {
self.ensure_node_exists(pred_id)?;
self.ensure_node_exists(succ_id)?;
let domain_id = domain
.map(|d| match d.into() {
DomainIdOrIdentifier::DomainIdentifier(ident) => {
self.retrieve_domain_from_identifier(ident)
}
DomainIdOrIdentifier::DomainId(domain_id) => {
self.ensure_domain_exists(domain_id).map(|_| domain_id)
}
})
.transpose()?;
self.edges_map
.get(&(pred_id, succ_id, domain_id))
.copied()
.and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge)))
.map_or_else(
|| {
let edge_id = self.edges.push(Edge {
strength,
relation,
pred: pred_id,
succ: succ_id,
domain: domain_id,
});
self.edges_map
.insert((pred_id, succ_id, domain_id), edge_id);
let pred = self
.nodes
.get_mut(pred_id)
.ok_or(GraphError::NodeNotFound)?;
pred.succs.push(edge_id);
let succ = self
.nodes
.get_mut(succ_id)
.ok_or(GraphError::NodeNotFound)?;
succ.preds.push(edge_id);
Ok(edge_id)
},
|(edge_id, edge)| {
if edge.strength == strength && edge.relation == relation {
Ok(edge_id)
} else {
Err(GraphError::ConflictingEdgeCreated)
}
},
)
}
pub fn make_all_aggregator<M: Metadata>(
&mut self,
nodes: &[(NodeId, Relation, Strength)],
info: Option<&'static str>,
metadata: Option<M>,
domain_id: Option<DomainId>,
) -> Result<NodeId, GraphError<V>> {
nodes
.iter()
.try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?;
let aggregator_id = self.nodes.push(Node::new(NodeType::AllAggregator));
let _aggregator_info_id = self.node_info.push(info);
let _node_metadata_id = self
.node_metadata
.push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));
for (node_id, relation, strength) in nodes {
self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?;
}
Ok(aggregator_id)
}
pub fn make_any_aggregator<M: Metadata>(
&mut self,
nodes: &[(NodeId, Relation, Strength)],
info: Option<&'static str>,
metadata: Option<M>,
domain_id: Option<DomainId>,
) -> Result<NodeId, GraphError<V>> {
nodes
.iter()
.try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?;
let aggregator_id = self.nodes.push(Node::new(NodeType::AnyAggregator));
let _aggregator_info_id = self.node_info.push(info);
let _node_metadata_id = self
.node_metadata
.push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));
for (node_id, relation, strength) in nodes {
self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?;
}
Ok(aggregator_id)
}
pub fn make_in_aggregator<M: Metadata>(
&mut self,
values: Vec<V>,
info: Option<&'static str>,
metadata: Option<M>,
) -> Result<NodeId, GraphError<V>> {
let key = values
.first()
.ok_or(GraphError::NoInAggregatorValues)?
.get_key();
for val in &values {
if val.get_key() != key {
Err(GraphError::MalformedGraph {
reason: "Values for 'In' aggregator not of same key".to_string(),
})?;
}
}
let node_id = self
.nodes
.push(Node::new(NodeType::InAggregator(FxHashSet::from_iter(
values,
))));
let _aggregator_info_id = self.node_info.push(info);
let _node_metadata_id = self
.node_metadata
.push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));
Ok(node_id)
}
fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError<V>> {
if self.nodes.contains_key(id) {
Ok(())
} else {
Err(GraphError::NodeNotFound)
}
}
fn ensure_domain_exists(&self, id: DomainId) -> Result<(), GraphError<V>> {
if self.domain.contains_key(id) {
Ok(())
} else {
Err(GraphError::DomainNotFound)
}
}
}
| 1,988 | 2,352 |
hyperswitch | crates/hyperswitch_constraint_graph/src/lib.rs | .rs | pub mod builder;
mod dense_map;
pub mod error;
pub mod graph;
pub mod types;
pub use builder::ConstraintGraphBuilder;
pub use error::{AnalysisTrace, GraphError};
pub use graph::ConstraintGraph;
#[cfg(feature = "viz")]
pub use types::NodeViz;
pub use types::{
CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization,
Node, NodeId, NodeValue, Relation, Strength, ValueNode,
};
| 105 | 2,353 |
hyperswitch | crates/hyperswitch_constraint_graph/src/error.rs | .rs | use std::sync::{Arc, Weak};
use crate::types::{Metadata, NodeValue, Relation, RelationResolution, ValueNode};
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "predecessor", rename_all = "snake_case")]
pub enum ValueTracePredecessor<V: ValueNode> {
Mandatory(Box<Weak<AnalysisTrace<V>>>),
OneOf(Vec<Weak<AnalysisTrace<V>>>),
}
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "trace", rename_all = "snake_case")]
pub enum AnalysisTrace<V: ValueNode> {
Value {
value: NodeValue<V>,
relation: Relation,
predecessors: Option<ValueTracePredecessor<V>>,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
AllAggregation {
unsatisfied: Vec<Weak<AnalysisTrace<V>>>,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
AnyAggregation {
unsatisfied: Vec<Weak<AnalysisTrace<V>>>,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
InAggregation {
expected: Vec<V>,
found: Option<V>,
relation: Relation,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
Contradiction {
relation: RelationResolution,
},
}
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum GraphError<V: ValueNode> {
#[error("An edge was not found in the graph")]
EdgeNotFound,
#[error("Attempted to create a conflicting edge between two nodes")]
ConflictingEdgeCreated,
#[error("Cycle detected in graph")]
CycleDetected,
#[error("Domain wasn't found in the Graph")]
DomainNotFound,
#[error("Malformed Graph: {reason}")]
MalformedGraph { reason: String },
#[error("A node was not found in the graph")]
NodeNotFound,
#[error("A value node was not found: {0:#?}")]
ValueNodeNotFound(V),
#[error("No values provided for an 'in' aggregator node")]
NoInAggregatorValues,
#[error("Error during analysis: {0:#?}")]
AnalysisError(Weak<AnalysisTrace<V>>),
}
impl<V: ValueNode> GraphError<V> {
pub fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace<V>>, Self> {
match self {
Self::AnalysisError(trace) => Ok(trace),
_ => Err(self),
}
}
}
| 587 | 2,354 |
hyperswitch | crates/hyperswitch_constraint_graph/src/dense_map.rs | .rs | use std::{fmt, iter, marker::PhantomData, ops, slice, vec};
pub trait EntityId {
fn get_id(&self) -> usize;
fn with_id(id: usize) -> Self;
}
macro_rules! impl_entity {
($name:ident) => {
impl $crate::dense_map::EntityId for $name {
#[inline]
fn get_id(&self) -> usize {
self.0
}
#[inline]
fn with_id(id: usize) -> Self {
Self(id)
}
}
};
}
pub(crate) use impl_entity;
pub struct DenseMap<K, V> {
data: Vec<V>,
_marker: PhantomData<K>,
}
impl<K, V> DenseMap<K, V> {
pub fn new() -> Self {
Self {
data: Vec::new(),
_marker: PhantomData,
}
}
}
impl<K, V> Default for DenseMap<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K, V> DenseMap<K, V>
where
K: EntityId,
{
pub fn push(&mut self, elem: V) -> K {
let curr_len = self.data.len();
self.data.push(elem);
K::with_id(curr_len)
}
#[inline]
pub fn get(&self, idx: K) -> Option<&V> {
self.data.get(idx.get_id())
}
#[inline]
pub fn get_mut(&mut self, idx: K) -> Option<&mut V> {
self.data.get_mut(idx.get_id())
}
#[inline]
pub fn contains_key(&self, key: K) -> bool {
key.get_id() < self.data.len()
}
#[inline]
pub fn keys(&self) -> Keys<K> {
Keys::new(0..self.data.len())
}
#[inline]
pub fn into_keys(self) -> Keys<K> {
Keys::new(0..self.data.len())
}
#[inline]
pub fn values(&self) -> slice::Iter<'_, V> {
self.data.iter()
}
#[inline]
pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
self.data.iter_mut()
}
#[inline]
pub fn into_values(self) -> vec::IntoIter<V> {
self.data.into_iter()
}
#[inline]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter::new(self.data.iter())
}
#[inline]
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut::new(self.data.iter_mut())
}
}
impl<K, V> fmt::Debug for DenseMap<K, V>
where
K: EntityId + fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
pub struct Keys<K> {
inner: ops::Range<usize>,
_marker: PhantomData<K>,
}
impl<K> Keys<K> {
fn new(range: ops::Range<usize>) -> Self {
Self {
inner: range,
_marker: PhantomData,
}
}
}
impl<K> Iterator for Keys<K>
where
K: EntityId,
{
type Item = K;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(K::with_id)
}
}
pub struct Iter<'a, K, V> {
inner: iter::Enumerate<slice::Iter<'a, V>>,
_marker: PhantomData<K>,
}
impl<'a, K, V> Iter<'a, K, V> {
fn new(iter: slice::Iter<'a, V>) -> Self {
Self {
inner: iter.enumerate(),
_marker: PhantomData,
}
}
}
impl<'a, K, V> Iterator for Iter<'a, K, V>
where
K: EntityId,
{
type Item = (K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(id, val)| (K::with_id(id), val))
}
}
pub struct IterMut<'a, K, V> {
inner: iter::Enumerate<slice::IterMut<'a, V>>,
_marker: PhantomData<K>,
}
impl<'a, K, V> IterMut<'a, K, V> {
fn new(iter: slice::IterMut<'a, V>) -> Self {
Self {
inner: iter.enumerate(),
_marker: PhantomData,
}
}
}
impl<'a, K, V> Iterator for IterMut<'a, K, V>
where
K: EntityId,
{
type Item = (K, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(id, val)| (K::with_id(id), val))
}
}
pub struct IntoIter<K, V> {
inner: iter::Enumerate<vec::IntoIter<V>>,
_marker: PhantomData<K>,
}
impl<K, V> IntoIter<K, V> {
fn new(iter: vec::IntoIter<V>) -> Self {
Self {
inner: iter.enumerate(),
_marker: PhantomData,
}
}
}
impl<K, V> Iterator for IntoIter<K, V>
where
K: EntityId,
{
type Item = (K, V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(id, val)| (K::with_id(id), val))
}
}
impl<K, V> IntoIterator for DenseMap<K, V>
where
K: EntityId,
{
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
IntoIter::new(self.data.into_iter())
}
}
impl<K, V> FromIterator<V> for DenseMap<K, V>
where
K: EntityId,
{
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = V>,
{
Self {
data: Vec::from_iter(iter),
_marker: PhantomData,
}
}
}
| 1,406 | 2,355 |
hyperswitch | crates/router_derive/Cargo.toml | .toml | [package]
name = "router_derive"
description = "Utility macros for the `router` crate"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[lib]
proc-macro = true
doctest = false
[dependencies]
indexmap = "2.2.6"
proc-macro2 = "1.0.79"
quote = "1.0.35"
serde_json = "1.0.115"
strum = { version = "0.26.2", features = ["derive"] }
syn = { version = "2.0.57", features = ["full", "extra-traits"] } # the full feature does not seem to encompass all the features
[dev-dependencies]
diesel = { version = "2.2.3", features = ["postgres"] }
error-stack = "0.4.1"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
utoipa = "4.2.0"
common_utils = { version = "0.1.0", path = "../common_utils" }
[lints]
workspace = true
| 277 | 2,356 |
hyperswitch | crates/router_derive/README.md | .md | # `router_derive`
Utility macros for the `router` crate.
| 15 | 2,357 |
hyperswitch | crates/router_derive/src/lib.rs | .rs | //! Utility macros for the `router` crate.
#![warn(missing_docs)]
use syn::parse_macro_input;
use crate::macros::diesel::DieselEnumMeta;
mod macros;
/// Uses the [`Debug`][Debug] implementation of a type to derive its [`Display`][Display]
/// implementation.
///
/// Causes a compilation error if the type doesn't implement the [`Debug`][Debug] trait.
///
/// [Debug]: ::core::fmt::Debug
/// [Display]: ::core::fmt::Display
///
/// # Example
///
/// ```
/// use router_derive::DebugAsDisplay;
///
/// #[derive(Debug, DebugAsDisplay)]
/// struct Point {
/// x: f32,
/// y: f32,
/// }
///
/// #[derive(Debug, DebugAsDisplay)]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_derive(DebugAsDisplay)]
pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::debug_as_display_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database.
/// The enum is required to implement (or derive) the [`ToString`][ToString] and the
/// [`FromStr`][FromStr] traits for this derive macro to be used.
///
/// Works in tandem with the [`diesel_enum`][diesel_enum] attribute macro to achieve the desired
/// results.
///
/// [diesel_enum]: macro@crate::diesel_enum
/// [FromStr]: ::core::str::FromStr
/// [ToString]: ::std::string::ToString
///
/// # Example
///
/// ```
/// use router_derive::diesel_enum;
///
/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it
/// // yourself if required.
/// #[derive(strum::Display, strum::EnumString)]
/// #[derive(Debug)]
/// #[diesel_enum(storage_type = "db_enum")]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_derive(DieselEnum, attributes(storage_type))]
pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Similar to [`DieselEnum`] but uses text when storing in the database, this is to avoid
/// making changes to the database when the enum variants are added or modified
///
/// # Example
/// [DieselEnum]: macro@crate::diesel_enum
///
/// ```
/// use router_derive::{diesel_enum};
///
/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it
/// // yourself if required.
/// #[derive(strum::Display, strum::EnumString)]
/// #[derive(Debug)]
/// #[diesel_enum(storage_type = "text")]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_derive(DieselEnumText)]
pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens = macros::diesel_enum_text_derive_inner(&ast)
.unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database.
///
/// Storage Type can either be "text" or "db_enum"
/// Choosing text will store the enum as text in the database, whereas db_enum will map it to the
/// corresponding database enum
///
/// Works in tandem with the [`DieselEnum`][DieselEnum] derive macro to achieve the desired results.
/// The enum is required to implement (or derive) the [`ToString`][ToString] and the
/// [`FromStr`][FromStr] traits for the [`DieselEnum`][DieselEnum] derive macro to be used.
///
/// [DieselEnum]: crate::DieselEnum
/// [FromStr]: ::core::str::FromStr
/// [ToString]: ::std::string::ToString
///
/// # Example
///
/// ```
/// use router_derive::{diesel_enum};
///
/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it
/// // yourself if required. (Required by the DieselEnum derive macro.)
/// #[derive(strum::Display, strum::EnumString)]
/// #[derive(Debug)]
/// #[diesel_enum(storage_type = "text")]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_attribute]
pub fn diesel_enum(
args: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let args_parsed = parse_macro_input!(args as DieselEnumMeta);
let item = syn::parse_macro_input!(item as syn::ItemEnum);
macros::diesel::diesel_enum_attribute_macro(args_parsed, &item)
.unwrap_or_else(|error| error.to_compile_error())
.into()
}
/// A derive macro which generates the setter functions for any struct with fields
/// # Example
/// ```
/// use router_derive::Setter;
///
/// #[derive(Setter)]
/// struct Test {
/// test:u32
/// }
/// ```
/// The above Example will expand to
/// ```rust, ignore
/// impl Test {
/// fn set_test(&mut self, val: u32) -> &mut Self {
/// self.test = val;
/// self
/// }
/// }
/// ```
///
/// # Panics
///
/// Panics if a struct without named fields is provided as input to the macro
// FIXME: Remove allowed warnings, raise compile errors in a better manner instead of panicking
#[allow(clippy::panic, clippy::unwrap_used)]
#[proc_macro_derive(Setter, attributes(auth_based))]
pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
let ident = &input.ident;
// All the fields in the parent struct
let fields = if let syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),
..
}) = input.data
{
named
} else {
// FIXME: Use `compile_error!()` instead
panic!("You can't use this proc-macro on structs without fields");
};
// Methods in the build struct like if the struct is
// Struct i {n: u32}
// this will be
// pub fn set_n(&mut self,n: u32)
let build_methods = fields.iter().map(|f| {
let name = f.ident.as_ref().unwrap();
let method_name = format!("set_{name}");
let method_ident = syn::Ident::new(&method_name, name.span());
let ty = &f.ty;
if check_if_auth_based_attr_is_present(f, "auth_based") {
quote::quote! {
pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{
if is_merchant_flow {
self.#name = val;
}
self
}
}
} else {
quote::quote! {
pub fn #method_ident(&mut self, val:#ty)->&mut Self{
self.#name = val;
self
}
}
}
});
let output = quote::quote! {
#[automatically_derived]
impl #ident {
#(#build_methods)*
}
};
output.into()
}
#[inline]
fn check_if_auth_based_attr_is_present(f: &syn::Field, ident: &str) -> bool {
for i in f.attrs.iter() {
if i.path().is_ident(ident) {
return true;
}
}
false
}
/// Derives the [`Serialize`][Serialize] implementation for error responses that are returned by
/// the API server.
///
/// This macro can be only used with enums. In addition to deriving [`Serialize`][Serialize], this
/// macro provides three methods: `error_type()`, `error_code()` and `error_message()`. Each enum
/// variant must have three required fields:
///
/// - `error_type`: This must be an enum variant which is returned by the `error_type()` method.
/// - `code`: A string error code, returned by the `error_code()` method.
/// - `message`: A string error message, returned by the `error_message()` method. The message
/// provided will directly be passed to `format!()`.
///
/// The return type of the `error_type()` method is provided by the `error_type_enum` field
/// annotated to the entire enum. Thus, all enum variants provided to the `error_type` field must
/// be variants of the enum provided to `error_type_enum` field. In addition, the enum passed to
/// the `error_type_enum` field must implement [`Serialize`][Serialize].
///
/// **NOTE:** This macro does not implement the [`Display`][Display] trait.
///
/// # Example
///
/// ```
/// use router_derive::ApiError;
///
/// #[derive(Clone, Debug, serde::Serialize)]
/// enum ErrorType {
/// StartupError,
/// InternalError,
/// SerdeError,
/// }
///
/// #[derive(Debug, ApiError)]
/// #[error(error_type_enum = ErrorType)]
/// enum MyError {
/// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")]
/// ConfigurationError,
/// #[error(error_type = ErrorType::InternalError, code = "E002", message = "A database error occurred")]
/// DatabaseError,
/// #[error(error_type = ErrorType::SerdeError, code = "E003", message = "Failed to deserialize object")]
/// DeserializationError,
/// #[error(error_type = ErrorType::SerdeError, code = "E004", message = "Failed to serialize object")]
/// SerializationError,
/// }
///
/// impl ::std::fmt::Display for MyError {
/// fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
/// f.write_str(&self.error_message())
/// }
/// }
/// ```
///
/// # The Generated `Serialize` Implementation
///
/// - For a simple enum variant with no fields, the generated [`Serialize`][Serialize]
/// implementation has only three fields, `type`, `code` and `message`:
///
/// ```
/// # use router_derive::ApiError;
/// # #[derive(Clone, Debug, serde::Serialize)]
/// # enum ErrorType {
/// # StartupError,
/// # }
/// #[derive(Debug, ApiError)]
/// #[error(error_type_enum = ErrorType)]
/// enum MyError {
/// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")]
/// ConfigurationError,
/// // ...
/// }
/// # impl ::std::fmt::Display for MyError {
/// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
/// # f.write_str(&self.error_message())
/// # }
/// # }
///
/// let json = serde_json::json!({
/// "type": "StartupError",
/// "code": "E001",
/// "message": "Failed to read configuration"
/// });
/// assert_eq!(serde_json::to_value(MyError::ConfigurationError).unwrap(), json);
/// ```
///
/// - For an enum variant with named fields, the generated [`Serialize`][Serialize] implementation
/// includes three mandatory fields, `type`, `code` and `message`, and any other fields not
/// included in the message:
///
/// ```
/// # use router_derive::ApiError;
/// # #[derive(Clone, Debug, serde::Serialize)]
/// # enum ErrorType {
/// # StartupError,
/// # }
/// #[derive(Debug, ApiError)]
/// #[error(error_type_enum = ErrorType)]
/// enum MyError {
/// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration file: {file_path}")]
/// ConfigurationError { file_path: String, reason: String },
/// // ...
/// }
/// # impl ::std::fmt::Display for MyError {
/// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
/// # f.write_str(&self.error_message())
/// # }
/// # }
///
/// let json = serde_json::json!({
/// "type": "StartupError",
/// "code": "E001",
/// "message": "Failed to read configuration file: config.toml",
/// "reason": "File not found"
/// });
/// let error = MyError::ConfigurationError{
/// file_path: "config.toml".to_string(),
/// reason: "File not found".to_string(),
/// };
/// assert_eq!(serde_json::to_value(error).unwrap(), json);
/// ```
///
/// [Serialize]: https://docs.rs/serde/latest/serde/trait.Serialize.html
/// [Display]: ::core::fmt::Display
#[proc_macro_derive(ApiError, attributes(error))]
pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Derives the `core::payments::Operation` trait on a type with a default base
/// implementation.
///
/// ## Usage
/// On deriving, the conversion functions to be implemented need to be specified in an helper
/// attribute `#[operation(..)]`. To derive all conversion functions, use `#[operation(all)]`. To
/// derive specific conversion functions, pass the required identifiers to the attribute.
/// `#[operation(validate_request, get_tracker)]`. Available conversions are listed below :-
///
/// - validate_request
/// - get_tracker
/// - domain
/// - update_tracker
///
/// ## Example
/// ```rust, ignore
/// use router_derive::Operation;
///
/// #[derive(Operation)]
/// #[operation(all)]
/// struct Point {
/// x: u64,
/// y: u64
/// }
///
/// // The above will expand to this
/// const _: () = {
/// use crate::core::errors::RouterResult;
/// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest};
/// impl crate::core::payments::Operation for Point {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(self)
/// }
/// fn to_domain(&self) -> RouterResult<&dyn Domain> {
/// Ok(self)
/// }
/// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> {
/// Ok(self)
/// }
/// }
/// impl crate::core::payments::Operation for &Point {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(*self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(*self)
/// }
/// fn to_domain(&self) -> RouterResult<&dyn Domain> {
/// Ok(*self)
/// }
/// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> {
/// Ok(*self)
/// }
/// }
/// };
///
/// #[derive(Operation)]
/// #[operation(validate_request, get_tracker)]
/// struct Point3 {
/// x: u64,
/// y: u64,
/// z: u64
/// }
///
/// // The above will expand to this
/// const _: () = {
/// use crate::core::errors::RouterResult;
/// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest};
/// impl crate::core::payments::Operation for Point3 {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(self)
/// }
/// }
/// impl crate::core::payments::Operation for &Point3 {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(*self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(*self)
/// }
/// }
/// };
///
/// ```
///
/// The `const _: () = {}` allows us to import stuff with `use` without affecting the module
/// imports, since use statements are not allowed inside of impl blocks. This technique is
/// used by `diesel`.
#[proc_macro_derive(PaymentOperation, attributes(operation))]
pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::operation::operation_derive_inner(input)
.unwrap_or_else(|err| err.to_compile_error().into())
}
/// Generates different schemas with the ability to mark few fields as mandatory for certain schema
/// Usage
/// ```
/// use router_derive::PolymorphicSchema;
///
/// #[derive(PolymorphicSchema)]
/// #[generate_schemas(PaymentsCreateRequest, PaymentsConfirmRequest)]
/// struct PaymentsRequest {
/// #[mandatory_in(PaymentsCreateRequest = u64)]
/// amount: Option<u64>,
/// #[mandatory_in(PaymentsCreateRequest = String)]
/// currency: Option<String>,
/// payment_method: String,
/// }
/// ```
///
/// This will create two structs `PaymentsCreateRequest` and `PaymentsConfirmRequest` as follows
/// It will retain all the other attributes that are used in the original struct, and only consume
/// the #[mandatory_in] attribute to generate schemas
///
/// ```
/// #[derive(utoipa::ToSchema)]
/// struct PaymentsCreateRequest {
/// #[schema(required = true)]
/// amount: Option<u64>,
///
/// #[schema(required = true)]
/// currency: Option<String>,
///
/// payment_method: String,
/// }
///
/// #[derive(utoipa::ToSchema)]
/// struct PaymentsConfirmRequest {
/// amount: Option<u64>,
/// currency: Option<String>,
/// payment_method: String,
/// }
/// ```
#[proc_macro_derive(
PolymorphicSchema,
attributes(mandatory_in, generate_schemas, remove_in)
)]
pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::polymorphic_macro_derive_inner(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
/// Implements the `Validate` trait to check if the config variable is present
/// Usage
/// ```
/// use router_derive::ConfigValidate;
///
/// #[derive(ConfigValidate)]
/// struct ConnectorParams {
/// base_url: String,
/// }
///
/// enum ApplicationError {
/// InvalidConfigurationValueError(String),
/// }
///
/// #[derive(ConfigValidate)]
/// struct Connectors {
/// pub stripe: ConnectorParams,
/// pub checkout: ConnectorParams
/// }
/// ```
///
/// This will call the `validate()` function for all the fields in the struct
///
/// ```rust, ignore
/// impl Connectors {
/// fn validate(&self) -> Result<(), ApplicationError> {
/// self.stripe.validate()?;
/// self.checkout.validate()?;
/// }
/// }
/// ```
#[proc_macro_derive(ConfigValidate)]
pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::misc::validate_config(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
/// Generates the function to get the value out of enum variant
/// Usage
/// ```
/// use router_derive::TryGetEnumVariant;
///
/// impl std::fmt::Display for RedisError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
/// match self {
/// Self::UnknownResult => write!(f, "Unknown result")
/// }
/// }
/// }
///
/// impl std::error::Error for RedisError {}
///
/// #[derive(Debug)]
/// enum RedisError {
/// UnknownResult
/// }
///
/// #[derive(TryGetEnumVariant)]
/// #[error(RedisError::UnknownResult)]
/// enum RedisResult {
/// Set(String),
/// Get(i32)
/// }
/// ```
///
/// This will generate the function to get `String` and `i32` out of the variants
///
/// ```rust, ignore
/// impl RedisResult {
/// fn try_into_get(&self)-> Result<i32, RedisError> {
/// match self {
/// Self::Get(a) => Ok(a),
/// _=>Err(RedisError::UnknownResult)
/// }
/// }
///
/// fn try_into_set(&self)-> Result<String, RedisError> {
/// match self {
/// Self::Set(a) => Ok(a),
/// _=> Err(RedisError::UnknownResult)
/// }
/// }
/// }
/// ```
#[proc_macro_derive(TryGetEnumVariant, attributes(error))]
pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::try_get_enum::try_get_enum_variant(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
/// Uses the [`Serialize`] implementation of a type to derive a function implementation
/// for converting nested keys structure into a HashMap of key, value where key is in
/// the flattened form.
///
/// Example
///
/// ```
/// #[derive(Default, Serialize, FlatStruct)]
/// pub struct User {
/// name: String,
/// address: Address,
/// email: String,
/// }
///
/// #[derive(Default, Serialize)]
/// pub struct Address {
/// line1: String,
/// line2: String,
/// zip: String,
/// }
///
/// let user = User::default();
/// let flat_struct_map = user.flat_struct();
///
/// [
/// ("name", "Test"),
/// ("address.line1", "1397"),
/// ("address.line2", "Some street"),
/// ("address.zip", "941222"),
/// ("email", "test@example.com"),
/// ]
/// ```
#[proc_macro_derive(FlatStruct)]
pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as syn::DeriveInput);
let name = &input.ident;
let expanded = quote::quote! {
impl #name {
pub fn flat_struct(&self) -> std::collections::HashMap<String, String> {
use serde_json::Value;
use std::collections::HashMap;
fn flatten_value(
value: &Value,
prefix: &str,
result: &mut HashMap<String, String>
) {
match value {
Value::Object(map) => {
for (key, val) in map {
let new_key = if prefix.is_empty() {
key.to_string()
} else {
format!("{}.{}", prefix, key)
};
flatten_value(val, &new_key, result);
}
}
Value::String(s) => {
result.insert(prefix.to_string(), s.clone());
}
Value::Number(n) => {
result.insert(prefix.to_string(), n.to_string());
}
Value::Bool(b) => {
result.insert(prefix.to_string(), b.to_string());
}
_ => {}
}
}
let mut result = HashMap::new();
let value = serde_json::to_value(self).unwrap();
flatten_value(&value, "", &mut result);
result
}
}
};
proc_macro::TokenStream::from(expanded)
}
/// Generates the permissions enum and implematations for the permissions
///
/// **NOTE:** You have to make sure that all the identifiers used
/// in the macro input are present in the respective enums as well.
///
/// ## Usage
/// ```
/// use router_derive::generate_permissions;
///
/// enum Scope {
/// Read,
/// Write,
/// }
///
/// enum EntityType {
/// Profile,
/// Merchant,
/// Org,
/// }
///
/// enum Resource {
/// Payments,
/// Refunds,
/// }
///
/// generate_permissions! {
/// permissions: [
/// Payments: {
/// scopes: [Read, Write],
/// entities: [Profile, Merchant, Org]
/// },
/// Refunds: {
/// scopes: [Read],
/// entities: [Profile, Org]
/// }
/// ]
/// }
/// ```
/// This will generate the following enum.
/// ```
/// enum Permission {
/// ProfilePaymentsRead,
/// ProfilePaymentsWrite,
/// MerchantPaymentsRead,
/// MerchantPaymentsWrite,
/// OrgPaymentsRead,
/// OrgPaymentsWrite,
/// ProfileRefundsRead,
/// OrgRefundsRead,
/// ```
#[proc_macro]
pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
macros::generate_permissions_inner(input)
}
/// Generates the ToEncryptable trait for a type
///
/// This macro generates the temporary structs which has the fields that needs to be encrypted
///
/// fn to_encryptable: Convert the temp struct to a hashmap that can be sent over the network
/// fn from_encryptable: Convert the hashmap back to temp struct
#[proc_macro_derive(ToEncryption, attributes(encrypt))]
pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::derive_to_encryption(input)
.unwrap_or_else(|err| err.into_compile_error())
.into()
}
| 5,911 | 2,358 |
hyperswitch | crates/router_derive/src/macros.rs | .rs | pub(crate) mod api_error;
pub(crate) mod diesel;
pub(crate) mod generate_permissions;
pub(crate) mod generate_schema;
pub(crate) mod misc;
pub(crate) mod operation;
pub(crate) mod to_encryptable;
pub(crate) mod try_get_enum;
mod helpers;
use proc_macro2::TokenStream;
use quote::quote;
use syn::DeriveInput;
pub(crate) use self::{
api_error::api_error_derive_inner,
diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner},
generate_permissions::generate_permissions_inner,
generate_schema::polymorphic_macro_derive_inner,
to_encryptable::derive_to_encryption,
};
pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
Ok(quote! {
#[automatically_derived]
impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
f.write_str(&format!("{:?}", self))
}
}
})
}
| 282 | 2,359 |
hyperswitch | crates/router_derive/src/macros/api_error.rs | .rs | mod helpers;
use std::collections::HashMap;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
punctuated::Punctuated, token::Comma, Data, DeriveInput, Fields, Ident, ImplGenerics,
TypeGenerics, Variant, WhereClause,
};
use crate::macros::{
api_error::helpers::{
check_missing_attributes, get_unused_fields, ErrorTypeProperties, ErrorVariantProperties,
HasErrorTypeProperties, HasErrorVariantProperties,
},
helpers::non_enum_error,
};
pub(crate) fn api_error_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let variants = match &ast.data {
Data::Enum(e) => &e.variants,
_ => return Err(non_enum_error()),
};
let type_properties = ast.get_type_properties()?;
let mut variants_properties_map = HashMap::new();
for variant in variants {
let variant_properties = variant.get_variant_properties()?;
check_missing_attributes(variant, &variant_properties)?;
variants_properties_map.insert(variant, variant_properties);
}
let error_type_fn = implement_error_type(name, &type_properties, &variants_properties_map);
let error_code_fn = implement_error_code(name, &variants_properties_map);
let error_message_fn = implement_error_message(name, &variants_properties_map);
let serialize_impl = implement_serialize(
name,
(&impl_generics, &ty_generics, where_clause),
&type_properties,
&variants_properties_map,
);
Ok(quote! {
#[automatically_derived]
impl #impl_generics std::error::Error for #name #ty_generics #where_clause {}
#[automatically_derived]
impl #impl_generics #name #ty_generics #where_clause {
#error_type_fn
#error_code_fn
#error_message_fn
}
#serialize_impl
})
}
fn implement_error_type(
enum_name: &Ident,
type_properties: &ErrorTypeProperties,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(..) => quote! { {..} },
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type = properties.error_type.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => #error_type });
}
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type_enum = type_properties.error_type_enum.as_ref().unwrap();
quote! {
pub fn error_type(&self) -> #error_type_enum {
match self {
#(#arms),*
}
}
}
}
fn implement_error_code(
enum_name: &Ident,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(..) => quote! { {..} },
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_code = properties.code.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => #error_code.to_string() });
}
quote! {
pub fn error_code(&self) -> String {
match self {
#(#arms),*
}
}
}
}
fn implement_error_message(
enum_name: &Ident,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(ref fields) => {
let fields = fields
.named
.iter()
.map(|f| {
// Safety: Named fields are guaranteed to have an identifier.
#[allow(clippy::unwrap_used)]
f.ident.as_ref().unwrap()
})
.collect::<Punctuated<&Ident, Comma>>();
quote! { {#fields} }
}
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_message = properties.message.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => format!(#error_message) });
}
quote! {
pub fn error_message(&self) -> String {
match self {
#(#arms),*
}
}
}
}
fn implement_serialize(
enum_name: &Ident,
generics: (&ImplGenerics<'_>, &TypeGenerics<'_>, Option<&WhereClause>),
type_properties: &ErrorTypeProperties,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = generics;
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(ref fields) => {
let fields = fields
.named
.iter()
.map(|f| {
// Safety: Named fields are guaranteed to have an identifier.
#[allow(clippy::unwrap_used)]
f.ident.as_ref().unwrap()
})
.collect::<Punctuated<&Ident, Comma>>();
quote! { {#fields} }
}
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_message = properties.message.as_ref().unwrap();
let msg_unused_fields =
get_unused_fields(&variant.fields, &error_message.value(), &properties.ignore);
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type_enum = type_properties.error_type_enum.as_ref().unwrap();
let response_definition = if msg_unused_fields.is_empty() {
quote! {
#[derive(Clone, Debug, serde::Serialize)]
struct ErrorResponse {
#[serde(rename = "type")]
error_type: #error_type_enum,
code: String,
message: String,
}
}
} else {
let mut extra_fields = Vec::new();
for field in &msg_unused_fields {
let vis = &field.vis;
// Safety: `msq_unused_fields` is expected to contain named fields only.
#[allow(clippy::unwrap_used)]
let ident = &field.ident.as_ref().unwrap();
let ty = &field.ty;
extra_fields.push(quote! { #vis #ident: #ty });
}
quote! {
#[derive(Clone, Debug, serde::Serialize)]
struct ErrorResponse #ty_generics #where_clause {
#[serde(rename = "type")]
error_type: #error_type_enum,
code: String,
message: String,
#(#extra_fields),*
}
}
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type = properties.error_type.as_ref().unwrap();
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let code = properties.code.as_ref().unwrap();
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let message = properties.message.as_ref().unwrap();
let extra_fields = msg_unused_fields
.iter()
.map(|field| {
// Safety: `extra_fields` is expected to contain named fields only.
#[allow(clippy::unwrap_used)]
let field_name = field.ident.as_ref().unwrap();
quote! { #field_name: #field_name.to_owned() }
})
.collect::<Vec<TokenStream>>();
arms.push(quote! {
#enum_name::#ident #params => {
#response_definition
let response = ErrorResponse {
error_type: #error_type,
code: #code.to_string(),
message: format!(#message),
#(#extra_fields),*
};
response.serialize(serializer)
}
});
}
quote! {
#[automatically_derived]
impl #impl_generics serde::Serialize for #enum_name #ty_generics #where_clause {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
#(#arms),*
}
}
}
}
}
| 2,061 | 2,360 |
hyperswitch | crates/router_derive/src/macros/generate_schema.rs | .rs | use std::collections::{HashMap, HashSet};
use indexmap::IndexMap;
use syn::{self, parse::Parse, parse_quote, punctuated::Punctuated, Token};
use crate::macros::helpers;
/// Parse schemas from attribute
/// Example
///
/// #[mandatory_in(PaymentsCreateRequest, PaymentsUpdateRequest)]
/// would return
///
/// [PaymentsCreateRequest, PaymentsUpdateRequest]
fn get_inner_path_ident(attribute: &syn::Attribute) -> syn::Result<Vec<syn::Ident>> {
Ok(attribute
.parse_args_with(Punctuated::<syn::Ident, Token![,]>::parse_terminated)?
.into_iter()
.collect::<Vec<_>>())
}
#[allow(dead_code)]
/// Get the type of field
fn get_field_type(field_type: syn::Type) -> syn::Result<syn::Ident> {
if let syn::Type::Path(path) = field_type {
path.path
.segments
.last()
.map(|last_path_segment| last_path_segment.ident.to_owned())
.ok_or(syn::Error::new(
proc_macro2::Span::call_site(),
"Atleast one ident must be specified",
))
} else {
Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
))
}
}
#[allow(dead_code)]
/// Get the inner type of option
fn get_inner_option_type(field: &syn::Type) -> syn::Result<syn::Ident> {
if let syn::Type::Path(ref path) = &field {
if let Some(segment) = path.path.segments.last() {
if let syn::PathArguments::AngleBracketed(ref args) = &segment.arguments {
if let Some(syn::GenericArgument::Type(ty)) = args.args.first() {
return get_field_type(ty.clone());
}
}
}
}
Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
))
}
mod schema_keyword {
use syn::custom_keyword;
custom_keyword!(schema);
}
#[derive(Debug, Clone)]
pub struct SchemaMeta {
struct_name: syn::Ident,
type_ident: syn::Ident,
}
/// parse #[mandatory_in(PaymentsCreateRequest = u64)]
impl Parse for SchemaMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let struct_name = input.parse::<syn::Ident>()?;
input.parse::<syn::Token![=]>()?;
let type_ident = input.parse::<syn::Ident>()?;
Ok(Self {
struct_name,
type_ident,
})
}
}
impl quote::ToTokens for SchemaMeta {
fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {}
}
pub fn polymorphic_macro_derive_inner(
input: syn::DeriveInput,
) -> syn::Result<proc_macro2::TokenStream> {
let schemas_to_create =
helpers::get_metadata_inner::<syn::Ident>("generate_schemas", &input.attrs)?;
let fields = helpers::get_struct_fields(input.data)
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?;
// Go through all the fields and create a mapping of required fields for a schema
// PaymentsCreate -> ["amount","currency"]
// This will be stored in the hashmap with key as
// required_fields -> ((amount, PaymentsCreate), (currency, PaymentsCreate))
// and values as the type
//
// (amount, PaymentsCreate) -> Amount
let mut required_fields = HashMap::<(syn::Ident, syn::Ident), syn::Ident>::new();
// These fields will be removed in the schema
// PaymentsUpdate -> ["client_secret"]
// This will be stored in a hashset
// hide_fields -> ((client_secret, PaymentsUpdate))
let mut hide_fields = HashSet::<(syn::Ident, syn::Ident)>::new();
let mut all_fields = IndexMap::<syn::Field, Vec<syn::Attribute>>::new();
for field in fields {
// Partition the attributes of a field into two vectors
// One with #[mandatory_in] attributes present
// Rest of the attributes ( include only the schema attribute, serde is not required)
let (mandatory_attribute, other_attributes) = field
.attrs
.iter()
.partition::<Vec<_>, _>(|attribute| attribute.path().is_ident("mandatory_in"));
let hidden_fields = field
.attrs
.iter()
.filter(|attribute| attribute.path().is_ident("remove_in"))
.collect::<Vec<_>>();
// Other attributes ( schema ) are to be printed as is
other_attributes
.iter()
.filter(|attribute| {
attribute.path().is_ident("schema") || attribute.path().is_ident("doc")
})
.for_each(|attribute| {
// Since attributes will be modified, the field should not contain any attributes
// So create a field, with previous attributes removed
let mut field_without_attributes = field.clone();
field_without_attributes.attrs.clear();
all_fields
.entry(field_without_attributes.to_owned())
.or_default()
.push(attribute.to_owned().to_owned());
});
// Mandatory attributes are to be inserted into hashset
// The hashset will store it in this format
// ("amount", PaymentsCreateRequest)
// ("currency", PaymentsConfirmRequest)
//
// For these attributes, we need to later add #[schema(required = true)] attribute
let field_ident = field.ident.ok_or(syn::Error::new(
proc_macro2::Span::call_site(),
"Cannot use `mandatory_in` on unnamed fields",
))?;
// Parse the #[mandatory_in(PaymentsCreateRequest = u64)] and insert into hashmap
// key -> ("amount", PaymentsCreateRequest)
// value -> u64
if let Some(mandatory_in_attribute) =
helpers::get_metadata_inner::<SchemaMeta>("mandatory_in", mandatory_attribute)?.first()
{
let key = (
field_ident.clone(),
mandatory_in_attribute.struct_name.clone(),
);
let value = mandatory_in_attribute.type_ident.clone();
required_fields.insert(key, value);
}
// Hidden fields are to be inserted in the Hashset
// The hashset will store it in this format
// ("client_secret", PaymentsUpdate)
//
// These fields will not be added to the struct
_ = hidden_fields
.iter()
// Filter only #[mandatory_in] attributes
.map(|&attribute| get_inner_path_ident(attribute))
.try_for_each(|schemas| {
let res = schemas
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?
.iter()
.map(|schema| (field_ident.clone(), schema.to_owned()))
.collect::<HashSet<_>>();
hide_fields.extend(res);
Ok::<_, syn::Error>(())
});
}
// iterate over the schemas and build them with their fields
let schemas = schemas_to_create
.iter()
.map(|schema| {
let fields = all_fields
.iter()
.filter_map(|(field, attributes)| {
let mut final_attributes = attributes.clone();
if let Some(field_ident) = field.ident.to_owned() {
// If the field is required for this schema, then add
// #[schema(value_type = type)] for this field
if let Some(required_field_type) =
required_fields.get(&(field_ident.clone(), schema.to_owned()))
{
// This is a required field in the Schema
// Add the value type and remove original value type ( if present )
let attribute_without_schema_type = attributes
.iter()
.filter(|attribute| !attribute.path().is_ident("schema"))
.map(Clone::clone)
.collect::<Vec<_>>();
final_attributes = attribute_without_schema_type;
let value_type_attribute: syn::Attribute =
parse_quote!(#[schema(value_type = #required_field_type)]);
final_attributes.push(value_type_attribute);
}
}
// If the field is to be not shown then
let is_hidden_field = field
.ident
.clone()
.map(|field_ident| hide_fields.contains(&(field_ident, schema.to_owned())))
.unwrap_or(false);
if is_hidden_field {
None
} else {
Some(quote::quote! {
#(#final_attributes)*
#field,
})
}
})
.collect::<Vec<_>>();
quote::quote! {
#[derive(utoipa::ToSchema)]
pub struct #schema {
#(#fields)*
}
}
})
.collect::<Vec<_>>();
Ok(quote::quote! {
#(#schemas)*
})
}
| 1,923 | 2,361 |
hyperswitch | crates/router_derive/src/macros/try_get_enum.rs | .rs | use proc_macro2::Span;
use quote::ToTokens;
use syn::{parse::Parse, punctuated::Punctuated};
mod try_get_keyword {
use syn::custom_keyword;
custom_keyword!(error_type);
}
#[derive(Debug)]
pub struct TryGetEnumMeta {
error_type: syn::Ident,
variant: syn::Ident,
}
impl Parse for TryGetEnumMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let error_type = input.parse()?;
_ = input.parse::<syn::Token![::]>()?;
let variant = input.parse()?;
Ok(Self {
error_type,
variant,
})
}
}
trait TryGetDeriveInputExt {
/// Get all the error metadata associated with an enum.
fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>>;
}
impl TryGetDeriveInputExt for syn::DeriveInput {
fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>> {
super::helpers::get_metadata_inner("error", &self.attrs)
}
}
impl ToTokens for TryGetEnumMeta {
fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {}
}
/// Try and get the variants for an enum
pub fn try_get_enum_variant(
input: syn::DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let name = &input.ident;
let parsed_error_type = input.get_metadata()?;
let (error_type, error_variant) = parsed_error_type
.first()
.ok_or(syn::Error::new(
Span::call_site(),
"One error should be specified",
))
.map(|error_struct| (&error_struct.error_type, &error_struct.variant))?;
let (impl_generics, generics, where_clause) = input.generics.split_for_impl();
let variants = get_enum_variants(&input.data)?;
let try_into_fns = variants.iter().map(|variant| {
let variant_name = &variant.ident;
let variant_field = get_enum_variant_field(variant)?;
let variant_types = variant_field.iter().map(|f|f.ty.clone());
let try_into_fn = syn::Ident::new(
&format!("try_into_{}", variant_name.to_string().to_lowercase()),
Span::call_site(),
);
Ok(quote::quote! {
pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> {
match self {
Self::#variant_name(inner) => Ok(inner),
_=> Err(error_stack::report!(#error_type::#error_variant)),
}
}
})
}).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?;
let expanded = quote::quote! {
impl #impl_generics #name #generics #where_clause {
#(#try_into_fns)*
}
};
Ok(expanded)
}
/// Get variants from Enum
fn get_enum_variants(data: &syn::Data) -> syn::Result<Punctuated<syn::Variant, syn::token::Comma>> {
if let syn::Data::Enum(syn::DataEnum { variants, .. }) = data {
Ok(variants.clone())
} else {
Err(super::helpers::non_enum_error())
}
}
/// Get Field from an enum variant
fn get_enum_variant_field(
variant: &syn::Variant,
) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> {
let field = match variant.fields.clone() {
syn::Fields::Unnamed(un) => un.unnamed,
syn::Fields::Named(n) => n.named,
syn::Fields::Unit => {
return Err(super::helpers::syn_error(
Span::call_site(),
"The enum is a unit variant it's not supported",
))
}
};
Ok(field)
}
| 859 | 2,362 |
hyperswitch | crates/router_derive/src/macros/to_encryptable.rs | .rs | use std::iter::Iterator;
use quote::{format_ident, quote};
use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType};
use crate::macros::{helpers::get_struct_fields, misc::get_field_type};
pub struct FieldMeta {
_meta_type: Ident,
pub value: Ident,
}
impl Parse for FieldMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let _meta_type: Ident = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value: Ident = input.parse()?;
Ok(Self { _meta_type, value })
}
}
impl quote::ToTokens for FieldMeta {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.value.to_tokens(tokens);
}
}
fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> {
let attrs = &field.attrs;
attrs
.iter()
.flat_map(|s| s.parse_args::<FieldMeta>())
.find(|s| s._meta_type.eq("ty"))
}
fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> {
path.path
.segments
.last()
.and_then(|segment| match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args.args.first(),
_ => None,
})
.and_then(|arg| match arg {
syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()),
_ => None,
})
.ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
)
})
}
/// This function returns the inner most type recursively
/// For example:
///
/// In the case of `Encryptable<Secret<String>>> this returns String
fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> {
fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> {
match get_inner_type(&path) {
Ok(inner_path) => get_inner_type_recursive(inner_path),
Err(_) => Ok(path),
}
}
match ty {
SynType::Path(path) => {
let inner_path = get_inner_type_recursive(path)?;
inner_path
.path
.segments
.last()
.map(|last_segment| last_segment.ident.to_owned())
.ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"At least one ident must be specified",
)
})
}
_ => Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
)),
}
}
/// This returns the field which implement #[encrypt] attribute
fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> {
fields
.into_iter()
.filter(|field| {
field
.attrs
.iter()
.any(|attr| attr.path().is_ident("encrypt"))
})
.collect()
}
/// This function returns the inner most type of a field
fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> {
fields
.iter()
.flat_map(|field| {
get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name))
})
.collect()
}
/// The type of the struct for which the batch encryption/decryption needs to be implemented
#[derive(PartialEq, Copy, Clone)]
enum StructType {
Encrypted,
Decrypted,
DecryptedUpdate,
FromRequest,
Updated,
}
impl StructType {
/// Generates the fields for temporary structs which consists of the fields that should be
/// encrypted/decrypted
fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> {
fields
.iter()
.map(|(field, inner_ty)| {
let provided_ty = get_encryption_ty_meta(field);
let is_option = get_field_type(field.ty.clone())
.map(|f| f.eq("Option"))
.unwrap_or_default();
let ident = &field.ident;
let inner_ty = if let Some(ref ty) = provided_ty {
&ty.value
} else {
inner_ty
};
match (self, is_option) {
(Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> },
(Self::Encrypted, false) => quote! { pub #ident: Encryption },
(Self::Decrypted, true) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::Decrypted, false) => {
quote! { pub #ident: Encryptable<Secret<#inner_ty>> }
}
(Self::DecryptedUpdate, _) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::FromRequest, true) => {
quote! { pub #ident: Option<Secret<#inner_ty>> }
}
(Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> },
(Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> },
}
})
.collect()
}
/// Generates the ToEncryptable trait implementation
fn generate_impls(
self,
gen1: proc_macro2::TokenStream,
gen2: proc_macro2::TokenStream,
gen3: proc_macro2::TokenStream,
impl_st: proc_macro2::TokenStream,
inner: &[Field],
) -> proc_macro2::TokenStream {
let map_length = inner.len();
let to_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) }
} else {
quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) }
}
})
});
let from_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { #field_ident: map.remove(#field_ident_string) }
} else {
quote! {
#field_ident: map.remove(#field_ident_string).ok_or(
error_stack::report!(common_utils::errors::ParsingError::EncodeError(
"Unable to convert from HashMap",
))
)?
}
}
})
});
quote! {
impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st {
fn to_encryptable(self) -> FxHashMap<String, #gen3> {
let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default());
#(#to_encryptable_impl;)*
map
}
fn from_encryptable(
mut map: FxHashMap<String, Encryptable<#gen2>>,
) -> CustomResult<#gen1, common_utils::errors::ParsingError> {
Ok(#gen1 {
#(#from_encryptable_impl,)*
})
}
}
}
}
}
/// This function generates the temporary struct and ToEncryptable impls for the temporary structs
fn generate_to_encryptable(
struct_name: Ident,
fields: Vec<Field>,
) -> syn::Result<proc_macro2::TokenStream> {
let struct_types = [
// The first two are to be used as return types we do not need to implement ToEncryptable
// on it
("Decrypted", StructType::Decrypted),
("DecryptedUpdate", StructType::DecryptedUpdate),
("FromRequestEncryptable", StructType::FromRequest),
("Encrypted", StructType::Encrypted),
("UpdateEncryptable", StructType::Updated),
];
let inner_types = get_field_and_inner_types(&fields);
let inner_type = inner_types.first().ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Please use the macro with attribute #[encrypt] on the fields you want to encrypt",
)
})?;
let provided_ty = get_encryption_ty_meta(&inner_type.0)
.map(|ty| ty.value.clone())
.unwrap_or(inner_type.1.clone());
let structs = struct_types.iter().map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let temp_fields = struct_type.generate_struct_fields(&inner_types);
quote! {
pub struct #name {
#(#temp_fields,)*
}
}
});
// These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs
// So skip the first two entries in the list
let impls = struct_types
.iter()
.skip(2)
.map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let impl_block = if *struct_type != StructType::DecryptedUpdate
|| *struct_type != StructType::Decrypted
{
let (gen1, gen2, gen3) = match struct_type {
StructType::FromRequest => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
StructType::Encrypted => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Encryption },
)
}
StructType::Updated => {
let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name);
(
quote! { #decrypted_update_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
//Unreachable statement
_ => (quote! {}, quote! {}, quote! {}),
};
struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields)
} else {
quote! {}
};
Ok(quote! {
#impl_block
})
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
#(#structs)*
#(#impls)*
})
}
pub fn derive_to_encryption(
input: syn::DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let struct_name = input.ident;
let fields = get_encryptable_fields(get_struct_fields(input.data)?);
generate_to_encryptable(struct_name, fields)
}
| 2,534 | 2,363 |
hyperswitch | crates/router_derive/src/macros/helpers.rs | .rs | use proc_macro2::Span;
use quote::ToTokens;
use syn::{parse::Parse, punctuated::Punctuated, spanned::Spanned, Attribute, Token};
pub fn non_enum_error() -> syn::Error {
syn::Error::new(Span::call_site(), "This macro only supports enums.")
}
pub(super) fn occurrence_error<T: ToTokens>(
first_keyword: T,
second_keyword: T,
attr: &str,
) -> syn::Error {
let mut error = syn::Error::new_spanned(
second_keyword,
format!("Found multiple occurrences of error({attr})"),
);
error.combine(syn::Error::new_spanned(first_keyword, "first one here"));
error
}
pub(super) fn syn_error(span: Span, message: &str) -> syn::Error {
syn::Error::new(span, message)
}
/// Get all the variants of a enum in the form of a string
pub fn get_possible_values_for_enum<T>() -> String
where
T: strum::IntoEnumIterator + ToString,
{
T::iter()
.map(|variants| variants.to_string())
.collect::<Vec<_>>()
.join(", ")
}
pub(super) fn get_metadata_inner<'a, T: Parse + Spanned>(
ident: &str,
attrs: impl IntoIterator<Item = &'a Attribute>,
) -> syn::Result<Vec<T>> {
attrs
.into_iter()
.filter(|attr| attr.path().is_ident(ident))
.try_fold(Vec::new(), |mut vec, attr| {
vec.extend(attr.parse_args_with(Punctuated::<T, Token![,]>::parse_terminated)?);
Ok(vec)
})
}
pub(super) fn get_struct_fields(
data: syn::Data,
) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> {
if let syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),
..
}) = data
{
Ok(named.to_owned())
} else {
Err(syn::Error::new(
Span::call_site(),
"This macro cannot be used on structs with no fields",
))
}
}
| 490 | 2,364 |
hyperswitch | crates/router_derive/src/macros/operation.rs | .rs | use std::str::FromStr;
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use strum::IntoEnumIterator;
use syn::{self, parse::Parse, DeriveInput};
use crate::macros::helpers;
#[derive(Debug, Clone, Copy, strum::EnumString, strum::EnumIter, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum Derives {
Sync,
Cancel,
Reject,
Capture,
ApproveData,
Authorize,
AuthorizeData,
SyncData,
CancelData,
CaptureData,
CompleteAuthorizeData,
RejectData,
SetupMandateData,
Start,
Verify,
Session,
SessionData,
IncrementalAuthorization,
IncrementalAuthorizationData,
SdkSessionUpdate,
SdkSessionUpdateData,
PostSessionTokens,
PostSessionTokensData,
}
impl Derives {
fn to_operation(
self,
fns: impl Iterator<Item = TokenStream> + Clone,
struct_name: &syn::Ident,
) -> TokenStream {
let req_type = Conversion::get_req_type(self);
quote! {
#[automatically_derived]
impl<F:Send+Clone+Sync> Operation<F,#req_type> for #struct_name {
type Data = PaymentData<F>;
#(#fns)*
}
}
}
fn to_ref_operation(
self,
ref_fns: impl Iterator<Item = TokenStream> + Clone,
struct_name: &syn::Ident,
) -> TokenStream {
let req_type = Conversion::get_req_type(self);
quote! {
#[automatically_derived]
impl<F:Send+Clone+Sync> Operation<F,#req_type> for &#struct_name {
type Data = PaymentData<F>;
#(#ref_fns)*
}
}
}
}
#[derive(Debug, Clone, strum::EnumString, strum::EnumIter, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum Conversion {
ValidateRequest,
GetTracker,
Domain,
UpdateTracker,
PostUpdateTracker,
All,
Invalid(String),
}
impl Conversion {
fn get_req_type(ident: Derives) -> syn::Ident {
match ident {
Derives::Authorize => syn::Ident::new("PaymentsRequest", Span::call_site()),
Derives::AuthorizeData => syn::Ident::new("PaymentsAuthorizeData", Span::call_site()),
Derives::Sync => syn::Ident::new("PaymentsRetrieveRequest", Span::call_site()),
Derives::SyncData => syn::Ident::new("PaymentsSyncData", Span::call_site()),
Derives::Cancel => syn::Ident::new("PaymentsCancelRequest", Span::call_site()),
Derives::CancelData => syn::Ident::new("PaymentsCancelData", Span::call_site()),
Derives::ApproveData => syn::Ident::new("PaymentsApproveData", Span::call_site()),
Derives::Reject => syn::Ident::new("PaymentsRejectRequest", Span::call_site()),
Derives::RejectData => syn::Ident::new("PaymentsRejectData", Span::call_site()),
Derives::Capture => syn::Ident::new("PaymentsCaptureRequest", Span::call_site()),
Derives::CaptureData => syn::Ident::new("PaymentsCaptureData", Span::call_site()),
Derives::CompleteAuthorizeData => {
syn::Ident::new("CompleteAuthorizeData", Span::call_site())
}
Derives::Start => syn::Ident::new("PaymentsStartRequest", Span::call_site()),
Derives::Verify => syn::Ident::new("VerifyRequest", Span::call_site()),
Derives::SetupMandateData => {
syn::Ident::new("SetupMandateRequestData", Span::call_site())
}
Derives::Session => syn::Ident::new("PaymentsSessionRequest", Span::call_site()),
Derives::SessionData => syn::Ident::new("PaymentsSessionData", Span::call_site()),
Derives::IncrementalAuthorization => {
syn::Ident::new("PaymentsIncrementalAuthorizationRequest", Span::call_site())
}
Derives::IncrementalAuthorizationData => {
syn::Ident::new("PaymentsIncrementalAuthorizationData", Span::call_site())
}
Derives::SdkSessionUpdate => {
syn::Ident::new("PaymentsDynamicTaxCalculationRequest", Span::call_site())
}
Derives::SdkSessionUpdateData => {
syn::Ident::new("SdkPaymentsSessionUpdateData", Span::call_site())
}
Derives::PostSessionTokens => {
syn::Ident::new("PaymentsPostSessionTokensRequest", Span::call_site())
}
Derives::PostSessionTokensData => {
syn::Ident::new("PaymentsPostSessionTokensData", Span::call_site())
}
}
}
fn to_function(&self, ident: Derives) -> TokenStream {
let req_type = Self::get_req_type(ident);
match self {
Self::ValidateRequest => quote! {
fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type, Self::Data> + Send + Sync)> {
Ok(self)
}
},
Self::GetTracker => quote! {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, #req_type> + Send + Sync)> {
Ok(self)
}
},
Self::Domain => quote! {
fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type, Self::Data>> {
Ok(self)
}
},
Self::UpdateTracker => quote! {
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, #req_type> + Send + Sync)> {
Ok(self)
}
},
Self::PostUpdateTracker => quote! {
fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> {
Ok(self)
}
},
Self::Invalid(s) => {
helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}"))
.to_compile_error()
}
Self::All => {
let validate_request = Self::ValidateRequest.to_function(ident);
let get_tracker = Self::GetTracker.to_function(ident);
let domain = Self::Domain.to_function(ident);
let update_tracker = Self::UpdateTracker.to_function(ident);
quote! {
#validate_request
#get_tracker
#domain
#update_tracker
}
}
}
}
fn to_ref_function(&self, ident: Derives) -> TokenStream {
let req_type = Self::get_req_type(ident);
match self {
Self::ValidateRequest => quote! {
fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, #req_type, Self::Data> + Send + Sync)> {
Ok(*self)
}
},
Self::GetTracker => quote! {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data,#req_type> + Send + Sync)> {
Ok(*self)
}
},
Self::Domain => quote! {
fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type, Self::Data>)> {
Ok(*self)
}
},
Self::UpdateTracker => quote! {
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data,#req_type> + Send + Sync)> {
Ok(*self)
}
},
Self::PostUpdateTracker => quote! {
fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> {
Ok(*self)
}
},
Self::Invalid(s) => {
helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}"))
.to_compile_error()
}
Self::All => {
let validate_request = Self::ValidateRequest.to_ref_function(ident);
let get_tracker = Self::GetTracker.to_ref_function(ident);
let domain = Self::Domain.to_ref_function(ident);
let update_tracker = Self::UpdateTracker.to_ref_function(ident);
quote! {
#validate_request
#get_tracker
#domain
#update_tracker
}
}
}
}
}
mod operations_keyword {
use syn::custom_keyword;
custom_keyword!(operations);
custom_keyword!(flow);
}
#[derive(Debug)]
pub enum OperationsEnumMeta {
Operations {
keyword: operations_keyword::operations,
value: Vec<Conversion>,
},
Flow {
keyword: operations_keyword::flow,
value: Vec<Derives>,
},
}
#[derive(Clone)]
pub struct OperationProperties {
operations: Vec<Conversion>,
flows: Vec<Derives>,
}
fn get_operation_properties(
operation_enums: Vec<OperationsEnumMeta>,
) -> syn::Result<OperationProperties> {
let mut operations = vec![];
let mut flows = vec![];
for operation in operation_enums {
match operation {
OperationsEnumMeta::Operations { value, .. } => {
operations = value;
}
OperationsEnumMeta::Flow { value, .. } => {
flows = value;
}
}
}
if operations.is_empty() {
Err(syn::Error::new(
Span::call_site(),
"atleast one operation must be specitied",
))?;
}
if flows.is_empty() {
Err(syn::Error::new(
Span::call_site(),
"atleast one flow must be specitied",
))?;
}
Ok(OperationProperties { operations, flows })
}
impl Parse for Derives {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let text = input.parse::<syn::LitStr>()?;
let value = text.value();
value.as_str().parse().map_err(|_| {
syn::Error::new_spanned(
&text,
format!(
"Unexpected value for flow: `{value}`. Possible values are `{}`",
helpers::get_possible_values_for_enum::<Self>()
),
)
})
}
}
impl Parse for Conversion {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let text = input.parse::<syn::LitStr>()?;
let value = text.value();
value.as_str().parse().map_err(|_| {
syn::Error::new_spanned(
&text,
format!(
"Unexpected value for operation: `{value}`. Possible values are `{}`",
helpers::get_possible_values_for_enum::<Self>()
),
)
})
}
}
fn parse_list_string<T>(list_string: String, keyword: &str) -> syn::Result<Vec<T>>
where
T: FromStr + IntoEnumIterator + ToString,
{
list_string
.split(',')
.map(str::trim)
.map(T::from_str)
.map(|result| {
result.map_err(|_| {
syn::Error::new(
Span::call_site(),
format!(
"Unexpected {keyword}, possible values are {}",
helpers::get_possible_values_for_enum::<T>()
),
)
})
})
.collect()
}
fn get_conversions(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Conversion>> {
let lit_str_list = input.parse::<syn::LitStr>()?;
parse_list_string(lit_str_list.value(), "operation")
}
fn get_derives(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Derives>> {
let lit_str_list = input.parse::<syn::LitStr>()?;
parse_list_string(lit_str_list.value(), "flow")
}
impl Parse for OperationsEnumMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(operations_keyword::operations) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = get_conversions(input)?;
Ok(Self::Operations { keyword, value })
} else if lookahead.peek(operations_keyword::flow) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = get_derives(input)?;
Ok(Self::Flow { keyword, value })
} else {
Err(lookahead.error())
}
}
}
trait OperationsDeriveInputExt {
/// Get all the error metadata associated with an enum.
fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>>;
}
impl OperationsDeriveInputExt for DeriveInput {
fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>> {
helpers::get_metadata_inner("operation", &self.attrs)
}
}
impl ToTokens for OperationsEnumMeta {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Operations { keyword, .. } => keyword.to_tokens(tokens),
Self::Flow { keyword, .. } => keyword.to_tokens(tokens),
}
}
}
pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::TokenStream> {
let struct_name = &input.ident;
let operations_meta = input.get_metadata()?;
let operation_properties = get_operation_properties(operations_meta)?;
let current_crate = syn::Ident::new("crate", Span::call_site());
let trait_derive = operation_properties
.clone()
.flows
.into_iter()
.map(|derive| {
let fns = operation_properties
.operations
.iter()
.map(|conversion| conversion.to_function(derive));
derive.to_operation(fns, struct_name)
})
.collect::<Vec<_>>();
let ref_trait_derive = operation_properties
.flows
.into_iter()
.map(|derive| {
let fns = operation_properties
.operations
.iter()
.map(|conversion| conversion.to_ref_function(derive));
derive.to_ref_operation(fns, struct_name)
})
.collect::<Vec<_>>();
let trait_derive = quote! {
#(#ref_trait_derive)* #(#trait_derive)*
};
let output = quote! {
const _: () = {
use #current_crate::core::errors::RouterResult;
use #current_crate::core::payments::{PaymentData,operations::{
ValidateRequest,
PostUpdateTracker,
GetTracker,
UpdateTracker,
}};
use #current_crate::types::{
SetupMandateRequestData,
PaymentsSyncData,
PaymentsCaptureData,
PaymentsCancelData,
PaymentsApproveData,
PaymentsRejectData,
PaymentsAuthorizeData,
PaymentsSessionData,
CompleteAuthorizeData,
PaymentsIncrementalAuthorizationData,
SdkPaymentsSessionUpdateData,
PaymentsPostSessionTokensData,
api::{
PaymentsCaptureRequest,
PaymentsCancelRequest,
PaymentsApproveRequest,
PaymentsRejectRequest,
PaymentsRetrieveRequest,
PaymentsRequest,
PaymentsStartRequest,
PaymentsSessionRequest,
VerifyRequest,
PaymentsDynamicTaxCalculationRequest,
PaymentsIncrementalAuthorizationRequest,
PaymentsPostSessionTokensRequest
}
};
#trait_derive
};
};
Ok(proc_macro::TokenStream::from(output))
}
| 3,384 | 2,365 |
hyperswitch | crates/router_derive/src/macros/misc.rs | .rs | pub fn get_field_type(field_type: syn::Type) -> Option<syn::Ident> {
if let syn::Type::Path(path) = field_type {
path.path
.segments
.last()
.map(|last_path_segment| last_path_segment.ident.to_owned())
} else {
None
}
}
/// Implement the `validate` function for the struct by calling `validate` function on the fields
pub fn validate_config(input: syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
let fields = super::helpers::get_struct_fields(input.data)
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?;
let struct_name = input.ident;
let function_expansions = fields
.into_iter()
.flat_map(|field| field.ident.to_owned().zip(get_field_type(field.ty)))
.filter_map(|(field_ident, field_type_ident)| {
// Check if a field is a leaf field, only String ( connector urls ) is supported for now
let field_ident_string = field_ident.to_string();
let is_optional_field = field_type_ident.eq("Option");
let is_secret_field = field_type_ident.eq("Secret");
// Do not call validate if it is an optional field
if !is_optional_field && !is_secret_field {
let is_leaf_field = field_type_ident.eq("String");
let validate_expansion = if is_leaf_field {
quote::quote!(common_utils::fp_utils::when(
self.#field_ident.is_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
format!("{} must not be empty for {}", #field_ident_string, parent_field).into(),
))
}
)?;
)
} else {
quote::quote!(
self.#field_ident.validate(#field_ident_string)?;
)
};
Some(validate_expansion)
} else {
None
}
})
.collect::<Vec<_>>();
let expansion = quote::quote! {
impl #struct_name {
/// Validates that the configuration provided for the `parent_field` does not contain empty or default values
pub fn validate(&self, parent_field: &str) -> Result<(), ApplicationError> {
#(#function_expansions)*
Ok(())
}
}
};
Ok(expansion)
}
| 511 | 2,366 |
hyperswitch | crates/router_derive/src/macros/generate_permissions.rs | .rs | use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
braced, bracketed,
parse::{Parse, ParseBuffer, ParseStream},
parse_macro_input,
punctuated::Punctuated,
token::Comma,
Ident, Token,
};
struct ResourceInput {
resource_name: Ident,
scopes: Punctuated<Ident, Token![,]>,
entities: Punctuated<Ident, Token![,]>,
}
struct Input {
permissions: Punctuated<ResourceInput, Token![,]>,
}
impl Parse for Input {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let (_permission_label, permissions) = parse_label_with_punctuated_data(input)?;
Ok(Self { permissions })
}
}
impl Parse for ResourceInput {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let resource_name: Ident = input.parse()?;
input.parse::<Token![:]>()?; // Expect ':'
let content;
braced!(content in input);
let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?;
content.parse::<Comma>()?;
let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?;
Ok(Self {
resource_name,
scopes,
entities,
})
}
}
fn parse_label_with_punctuated_data<T: Parse>(
input: &ParseBuffer<'_>,
) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> {
let label: Ident = input.parse()?;
input.parse::<Token![:]>()?; // Expect ':'
let content;
bracketed!(content in input); // Parse the list inside []
let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?;
Ok((label, data))
}
pub fn generate_permissions_inner(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as Input);
let res = input.permissions.iter();
let mut enum_keys = Vec::new();
let mut scope_impl_per = Vec::new();
let mut entity_impl_per = Vec::new();
let mut resource_impl_per = Vec::new();
let mut entity_impl_res = Vec::new();
for per in res {
let resource_name = &per.resource_name;
let mut permissions = Vec::new();
for scope in per.scopes.iter() {
for entity in per.entities.iter() {
let key = format_ident!("{}{}{}", entity, per.resource_name, scope);
enum_keys.push(quote! { #key });
scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope });
entity_impl_per.push(quote! { Permission::#key => EntityType::#entity });
resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name });
permissions.push(quote! { Permission::#key });
}
let entities_iter = per.entities.iter();
entity_impl_res
.push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] });
}
}
let expanded = quote! {
#[derive(
Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display
)]
pub enum Permission {
#(#enum_keys),*
}
impl Permission {
pub fn scope(&self) -> PermissionScope {
match self {
#(#scope_impl_per),*
}
}
pub fn entity_type(&self) -> EntityType {
match self {
#(#entity_impl_per),*
}
}
pub fn resource(&self) -> Resource {
match self {
#(#resource_impl_per),*
}
}
}
pub trait ResourceExt {
fn entities(&self) -> Vec<EntityType>;
}
impl ResourceExt for Resource {
fn entities(&self) -> Vec<EntityType> {
match self {
#(#entity_impl_res),*
}
}
}
};
expanded.into()
}
| 887 | 2,367 |
hyperswitch | crates/router_derive/src/macros/diesel.rs | .rs | use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{parse::Parse, Data, DeriveInput, ItemEnum};
use crate::macros::helpers;
pub(crate) fn diesel_enum_text_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
match &ast.data {
Data::Enum(_) => (),
_ => return Err(helpers::non_enum_error()),
};
Ok(quote! {
#[automatically_derived]
impl #impl_generics ::diesel::serialize::ToSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result {
use ::std::io::Write;
out.write_all(self.to_string().as_bytes())?;
Ok(::diesel::serialize::IsNull::No)
}
}
#[automatically_derived]
impl #impl_generics ::diesel::deserialize::FromSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> {
use ::core::str::FromStr;
Self::from_str(::core::str::from_utf8(value.as_bytes())?)
.map_err(|_| "Unrecognized enum variant".into())
}
}
})
}
pub(crate) fn diesel_enum_db_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
match &ast.data {
Data::Enum(_) => (),
_ => return Err(helpers::non_enum_error()),
};
let struct_name = format_ident!("Db{name}");
let type_name = format!("{name}");
Ok(quote! {
#[derive(::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug, ::diesel::QueryId, ::diesel::SqlType)]
#[diesel(postgres_type(name = #type_name))]
pub struct #struct_name;
#[automatically_derived]
impl #impl_generics ::diesel::serialize::ToSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result {
use ::std::io::Write;
out.write_all(self.to_string().as_bytes())?;
Ok(::diesel::serialize::IsNull::No)
}
}
#[automatically_derived]
impl #impl_generics ::diesel::deserialize::FromSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> {
use ::core::str::FromStr;
Self::from_str(::core::str::from_utf8(value.as_bytes())?)
.map_err(|_| "Unrecognized enum variant".into())
}
}
})
}
mod diesel_keyword {
use syn::custom_keyword;
custom_keyword!(storage_type);
custom_keyword!(db_enum);
custom_keyword!(text);
}
#[derive(Debug, strum::EnumString, strum::EnumIter, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum StorageType {
/// Store the Enum as Text value in the database
Text,
/// Store the Enum as Enum in the database. This requires a corresponding enum to be created
/// in the database with the same name
DbEnum,
}
#[derive(Debug)]
pub enum DieselEnumMeta {
StorageTypeEnum {
keyword: diesel_keyword::storage_type,
value: StorageType,
},
}
impl Parse for StorageType {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let text = input.parse::<syn::LitStr>()?;
let value = text.value();
value.as_str().parse().map_err(|_| {
syn::Error::new_spanned(
&text,
format!(
"Unexpected value for storage_type: `{value}`. Possible values are `{}`",
helpers::get_possible_values_for_enum::<Self>()
),
)
})
}
}
impl DieselEnumMeta {
pub fn get_storage_type(&self) -> &StorageType {
match self {
Self::StorageTypeEnum { value, .. } => value,
}
}
}
impl Parse for DieselEnumMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(diesel_keyword::storage_type) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = input.parse()?;
Ok(Self::StorageTypeEnum { keyword, value })
} else {
Err(lookahead.error())
}
}
}
impl ToTokens for DieselEnumMeta {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::StorageTypeEnum { keyword, .. } => keyword.to_tokens(tokens),
}
}
}
trait DieselDeriveInputExt {
/// Get all the error metadata associated with an enum.
fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>>;
}
impl DieselDeriveInputExt for DeriveInput {
fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>> {
helpers::get_metadata_inner("storage_type", &self.attrs)
}
}
pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let storage_type = ast.get_metadata()?;
match storage_type
.first()
.ok_or(syn::Error::new(
Span::call_site(),
"Storage type must be specified",
))?
.get_storage_type()
{
StorageType::Text => diesel_enum_text_derive_inner(ast),
StorageType::DbEnum => diesel_enum_db_enum_derive_inner(ast),
}
}
/// Based on the storage type, derive appropriate diesel traits
/// This will add the appropriate #[diesel(sql_type)]
/// Since the `FromSql` and `ToSql` have to be derived for all the enums, this will add the
/// `DieselEnum` derive trait.
pub(crate) fn diesel_enum_attribute_macro(
diesel_enum_meta: DieselEnumMeta,
item: &ItemEnum,
) -> syn::Result<TokenStream> {
let diesel_derives =
quote!(#[derive(diesel::AsExpression, diesel::FromSqlRow, router_derive::DieselEnum) ]);
match diesel_enum_meta {
DieselEnumMeta::StorageTypeEnum {
value: storage_type,
..
} => match storage_type {
StorageType::Text => Ok(quote! {
#diesel_derives
#[diesel(sql_type = ::diesel::sql_types::Text)]
#[storage_type(storage_type = "text")]
#item
}),
StorageType::DbEnum => {
let name = &item.ident;
let type_name = format_ident!("Db{name}");
Ok(quote! {
#diesel_derives
#[diesel(sql_type = #type_name)]
#[storage_type(storage_type= "db_enum")]
#item
})
}
},
}
}
| 1,740 | 2,368 |
hyperswitch | crates/router_derive/src/macros/api_error/helpers.rs | .rs | use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::{
parse::Parse, spanned::Spanned, DeriveInput, Field, Fields, LitStr, Token, TypePath, Variant,
};
use crate::macros::helpers::{get_metadata_inner, occurrence_error};
mod keyword {
use syn::custom_keyword;
// Enum metadata
custom_keyword!(error_type_enum);
// Variant metadata
custom_keyword!(error_type);
custom_keyword!(code);
custom_keyword!(message);
custom_keyword!(ignore);
}
enum EnumMeta {
ErrorTypeEnum {
keyword: keyword::error_type_enum,
value: TypePath,
},
}
impl Parse for EnumMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::error_type_enum) {
let keyword = input.parse()?;
input.parse::<Token![=]>()?;
let value = input.parse()?;
Ok(Self::ErrorTypeEnum { keyword, value })
} else {
Err(lookahead.error())
}
}
}
impl ToTokens for EnumMeta {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::ErrorTypeEnum { keyword, .. } => keyword.to_tokens(tokens),
}
}
}
trait DeriveInputExt {
/// Get all the error metadata associated with an enum.
fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>>;
}
impl DeriveInputExt for DeriveInput {
fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>> {
get_metadata_inner("error", &self.attrs)
}
}
pub(super) trait HasErrorTypeProperties {
fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties>;
}
#[derive(Clone, Debug, Default)]
pub(super) struct ErrorTypeProperties {
pub error_type_enum: Option<TypePath>,
}
impl HasErrorTypeProperties for DeriveInput {
fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties> {
let mut output = ErrorTypeProperties::default();
let mut error_type_enum_keyword = None;
for meta in self.get_metadata()? {
match meta {
EnumMeta::ErrorTypeEnum { keyword, value } => {
if let Some(first_keyword) = error_type_enum_keyword {
return Err(occurrence_error(first_keyword, keyword, "error_type_enum"));
}
error_type_enum_keyword = Some(keyword);
output.error_type_enum = Some(value);
}
}
}
if output.error_type_enum.is_none() {
return Err(syn::Error::new(
self.span(),
"error(error_type_enum) attribute not found",
));
}
Ok(output)
}
}
enum VariantMeta {
ErrorType {
keyword: keyword::error_type,
value: TypePath,
},
Code {
keyword: keyword::code,
value: LitStr,
},
Message {
keyword: keyword::message,
value: LitStr,
},
Ignore {
keyword: keyword::ignore,
value: LitStr,
},
}
impl Parse for VariantMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::error_type) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::ErrorType { keyword, value })
} else if lookahead.peek(keyword::code) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::Code { keyword, value })
} else if lookahead.peek(keyword::message) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::Message { keyword, value })
} else if lookahead.peek(keyword::ignore) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::Ignore { keyword, value })
} else {
Err(lookahead.error())
}
}
}
impl ToTokens for VariantMeta {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::ErrorType { keyword, .. } => keyword.to_tokens(tokens),
Self::Code { keyword, .. } => keyword.to_tokens(tokens),
Self::Message { keyword, .. } => keyword.to_tokens(tokens),
Self::Ignore { keyword, .. } => keyword.to_tokens(tokens),
}
}
}
trait VariantExt {
/// Get all the error metadata associated with an enum variant.
fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>>;
}
impl VariantExt for Variant {
fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>> {
get_metadata_inner("error", &self.attrs)
}
}
pub(super) trait HasErrorVariantProperties {
fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties>;
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(super) struct ErrorVariantProperties {
pub error_type: Option<TypePath>,
pub code: Option<LitStr>,
pub message: Option<LitStr>,
pub ignore: std::collections::HashSet<String>,
}
impl HasErrorVariantProperties for Variant {
fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties> {
let mut output = ErrorVariantProperties::default();
let mut error_type_keyword = None;
let mut code_keyword = None;
let mut message_keyword = None;
let mut ignore_keyword = None;
for meta in self.get_metadata()? {
match meta {
VariantMeta::ErrorType { keyword, value } => {
if let Some(first_keyword) = error_type_keyword {
return Err(occurrence_error(first_keyword, keyword, "error_type"));
}
error_type_keyword = Some(keyword);
output.error_type = Some(value);
}
VariantMeta::Code { keyword, value } => {
if let Some(first_keyword) = code_keyword {
return Err(occurrence_error(first_keyword, keyword, "code"));
}
code_keyword = Some(keyword);
output.code = Some(value);
}
VariantMeta::Message { keyword, value } => {
if let Some(first_keyword) = message_keyword {
return Err(occurrence_error(first_keyword, keyword, "message"));
}
message_keyword = Some(keyword);
output.message = Some(value);
}
VariantMeta::Ignore { keyword, value } => {
if let Some(first_keyword) = ignore_keyword {
return Err(occurrence_error(first_keyword, keyword, "ignore"));
}
ignore_keyword = Some(keyword);
output.ignore = value
.value()
.replace(' ', "")
.split(',')
.map(ToString::to_string)
.collect();
}
}
}
Ok(output)
}
}
fn missing_attribute_error(variant: &Variant, attr: &str) -> syn::Error {
syn::Error::new_spanned(variant, format!("{attr} must be specified"))
}
pub(super) fn check_missing_attributes(
variant: &Variant,
variant_properties: &ErrorVariantProperties,
) -> syn::Result<()> {
if variant_properties.error_type.is_none() {
return Err(missing_attribute_error(variant, "error_type"));
}
if variant_properties.code.is_none() {
return Err(missing_attribute_error(variant, "code"));
}
if variant_properties.message.is_none() {
return Err(missing_attribute_error(variant, "message"));
}
Ok(())
}
/// Get all the fields not used in the error message.
pub(super) fn get_unused_fields(
fields: &Fields,
message: &str,
ignore: &std::collections::HashSet<String>,
) -> Vec<Field> {
let fields = match fields {
Fields::Unit => Vec::new(),
Fields::Unnamed(_) => Vec::new(),
Fields::Named(fields) => fields.named.iter().cloned().collect(),
};
fields
.iter()
.filter(|&field| {
// Safety: Named fields are guaranteed to have an identifier.
#[allow(clippy::unwrap_used)]
let field_name = format!("{}", field.ident.as_ref().unwrap());
!message.contains(&field_name) && !ignore.contains(&field_name)
})
.cloned()
.collect()
}
| 1,826 | 2,369 |
hyperswitch | crates/payment_methods/Cargo.toml | .toml | [package]
name = "payment_methods"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
async-trait = "0.1.79"
dyn-clone = "1.0.17"
common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] }
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
[lints]
workspace = true
[features]
default = ["v1"]
v1 = ["hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1"]
v2 = [ "payment_methods_v2"]
payment_methods_v2 = [ "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] | 244 | 2,370 |
hyperswitch | crates/payment_methods/src/lib.rs | .rs | pub mod state;
| 4 | 2,371 |
hyperswitch | crates/payment_methods/src/state.rs | .rs | #[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
use common_utils::errors::CustomResult;
use common_utils::types::keymanager::KeyManagerState;
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
use hyperswitch_domain_models::{
merchant_account::MerchantAccount, payment_methods::PaymentMethod,
};
use hyperswitch_domain_models::{
merchant_key_store::MerchantKeyStore, payment_methods::PaymentMethodInterface,
};
use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore};
#[async_trait::async_trait]
pub trait PaymentMethodsStorageInterface:
Send + Sync + dyn_clone::DynClone + PaymentMethodInterface<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<MerchantKeyStore>,
pub key_manager_state: KeyManagerState,
}
impl From<&PaymentMethodsState> for KeyManagerState {
fn from(state: &PaymentMethodsState) -> Self {
state.key_manager_state.clone()
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
impl PaymentMethodsState {
pub async fn find_payment_method(
&self,
key_store: &MerchantKeyStore,
merchant_account: &MerchantAccount,
payment_method_id: String,
) -> CustomResult<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),
}
}
}
| 570 | 2,372 |
hyperswitch | crates/config_importer/Cargo.toml | .toml | [package]
name = "config_importer"
description = "Utility to convert a TOML configuration file to a list of environment variables"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
anyhow = "1.0.81"
clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] }
indexmap = { version = "2.2.6", optional = true }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
toml = { version = "0.8.12", default-features = false, features = ["parse"] }
[features]
default = ["preserve_order"]
preserve_order = ["dep:indexmap", "serde_json/preserve_order", "toml/preserve_order"]
[lints]
workspace = true
| 248 | 2,373 |
hyperswitch | crates/config_importer/README.md | .md | # config_importer
A simple utility tool to import a Hyperswitch TOML configuration file, convert
it into environment variable key-value pairs, and export it in the specified
format.
As of now, it supports only exporting the environment variables to a JSON format
compatible with Kubernetes, but it can be easily extended to export to a YAML
format compatible with Kubernetes or the env file format.
## Usage
You can find the usage information from the help message by specifying the
`--help` flag:
```shell
cargo run --bin config_importer -- --help
```
### Specifying the output location
If the `--output-file` flag is not specified, the utility prints the output to
stdout.
If you would like to write the output to a file instead, you can specify the
`--output-file` flag with the path to the output file:
```shell
cargo run --bin config_importer -- --input-file config/development.toml --output-file config/development.json
```
### Specifying a different prefix
If the `--prefix` flag is not specified, the default prefix `ROUTER` is
considered, which generates the environment variables accepted by the `router`
binary/application.
If you'd want to generate environment variables for the `drainer`
binary/application, then you can specify the `--prefix` flag with value
`drainer` (or `DRAINER`, both work).
```shell
cargo run --bin config_importer -- --input-file config/drainer.toml --prefix drainer
```
| 323 | 2,374 |
hyperswitch | crates/config_importer/src/main.rs | .rs | mod cli;
use std::io::{BufWriter, Write};
use anyhow::Context;
/// The separator used in environment variable names.
const ENV_VAR_SEPARATOR: &str = "__";
#[cfg(not(feature = "preserve_order"))]
type EnvironmentVariableMap = std::collections::HashMap<String, String>;
#[cfg(feature = "preserve_order")]
type EnvironmentVariableMap = indexmap::IndexMap<String, String>;
fn main() -> anyhow::Result<()> {
let args = <cli::Args as clap::Parser>::parse();
// Read input TOML file
let toml_contents =
std::fs::read_to_string(args.input_file).context("Failed to read input file")?;
let table = toml_contents
.parse::<toml::Table>()
.context("Failed to parse TOML file contents")?;
// Parse TOML file contents to a `HashMap` of environment variable name and value pairs
let env_vars = table
.iter()
.flat_map(|(key, value)| process_toml_value(&args.prefix, key, value))
.collect::<EnvironmentVariableMap>();
let writer: BufWriter<Box<dyn Write>> = match args.output_file {
// Write to file if output file is specified
Some(file) => BufWriter::new(Box::new(
std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(file)
.context("Failed to open output file")?,
)),
// Write to stdout otherwise
None => BufWriter::new(Box::new(std::io::stdout().lock())),
};
// Write environment variables in specified format
match args.output_format {
cli::OutputFormat::KubernetesJson => {
let k8s_env_vars = env_vars
.into_iter()
.map(|(name, value)| KubernetesEnvironmentVariable { name, value })
.collect::<Vec<_>>();
serde_json::to_writer_pretty(writer, &k8s_env_vars)
.context("Failed to serialize environment variables as JSON")?
}
}
Ok(())
}
fn process_toml_value(
prefix: impl std::fmt::Display + Clone,
key: impl std::fmt::Display + Clone,
value: &toml::Value,
) -> Vec<(String, String)> {
let key_with_prefix = format!("{prefix}{ENV_VAR_SEPARATOR}{key}").to_ascii_uppercase();
match value {
toml::Value::String(s) => vec![(key_with_prefix, s.to_owned())],
toml::Value::Integer(i) => vec![(key_with_prefix, i.to_string())],
toml::Value::Float(f) => vec![(key_with_prefix, f.to_string())],
toml::Value::Boolean(b) => vec![(key_with_prefix, b.to_string())],
toml::Value::Datetime(dt) => vec![(key_with_prefix, dt.to_string())],
toml::Value::Array(values) => {
if values.is_empty() {
return vec![(key_with_prefix, String::new())];
}
// This logic does not support / account for arrays of tables or arrays of arrays.
let (_processed_keys, processed_values) = values
.iter()
.flat_map(|v| process_toml_value(prefix.clone(), key.clone(), v))
.unzip::<_, _, Vec<String>, Vec<String>>();
vec![(key_with_prefix, processed_values.join(","))]
}
toml::Value::Table(map) => map
.into_iter()
.flat_map(|(k, v)| process_toml_value(key_with_prefix.clone(), k, v))
.collect(),
}
}
/// The Kubernetes environment variable structure containing a name and a value.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct KubernetesEnvironmentVariable {
name: String,
value: String,
}
| 841 | 2,375 |
hyperswitch | crates/config_importer/src/cli.rs | .rs | use std::path::PathBuf;
/// Utility to import a hyperswitch TOML configuration file, convert it into environment variable
/// key-value pairs, and export it in the specified format.
#[derive(clap::Parser, Debug)]
#[command(arg_required_else_help = true)]
pub(crate) struct Args {
/// Input TOML configuration file.
#[arg(short, long, value_name = "FILE")]
pub(crate) input_file: PathBuf,
/// The format to convert the environment variables to.
#[arg(
value_enum,
short = 'f',
long,
value_name = "FORMAT",
default_value = "kubernetes-json"
)]
pub(crate) output_format: OutputFormat,
/// Output file. Output will be written to stdout if not specified.
#[arg(short, long, value_name = "FILE")]
pub(crate) output_file: Option<PathBuf>,
/// Prefix to be used for each environment variable in the generated output.
#[arg(short, long, default_value = "ROUTER")]
pub(crate) prefix: String,
}
/// The output format to convert environment variables to.
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub(crate) enum OutputFormat {
/// Converts each environment variable to an object containing `name` and `value` fields.
///
/// ```json
/// {
/// "name": "ENVIRONMENT",
/// "value": "PRODUCTION"
/// }
/// ```
KubernetesJson,
}
| 319 | 2,376 |
hyperswitch | crates/hyperswitch_domain_models/Cargo.toml | .toml | [package]
name = "hyperswitch_domain_models"
description = "Represents the data/domain models used by the business layer"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
default = ["olap", "frm"]
encryption_service = []
olap = []
payouts = ["api_models/payouts"]
frm = ["api_models/frm"]
v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2", "common_types/v2"]
v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1", "common_types/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"]
dummy_connector = []
revenue_recovery= []
[dependencies]
# First party deps
api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] }
cards = { version = "0.1.0", path = "../cards" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics", "encryption_service", "keymanager"] }
common_types = { version = "0.1.0", path = "../common_types" }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }
masking = { version = "0.1.0", path = "../masking" }
router_derive = { version = "0.1.0", path = "../router_derive" }
router_env = { version = "0.1.0", path = "../router_env" }
# Third party deps
actix-web = "4.5.1"
async-trait = "0.1.79"
error-stack = "0.4.1"
futures = "0.3.30"
http = "0.2.12"
mime = "0.3.17"
rustc-hash = "1.1.0"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
serde_with = "3.7.0"
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
url = { version = "2.5.0", features = ["serde"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] }
[lints]
workspace = true
| 644 | 2,377 |
hyperswitch | crates/hyperswitch_domain_models/README.md | .md | # Hyperswitch domain models
Represents the data/domain models used by the business/domain layer | 19 | 2,378 |
hyperswitch | crates/hyperswitch_domain_models/src/behaviour.rs | .rs | use common_utils::{
errors::{CustomResult, ValidationError},
types::keymanager::{Identifier, KeyManagerState},
};
use masking::Secret;
/// Trait for converting domain types to storage models
#[async_trait::async_trait]
pub trait Conversion {
type DstType;
type NewDstType;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError>;
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized;
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError>;
}
#[async_trait::async_trait]
pub trait ReverseConversion<SrcType: Conversion> {
async fn convert(
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<SrcType, ValidationError>;
}
#[async_trait::async_trait]
impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T {
async fn convert(
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<U, ValidationError> {
U::convert_back(state, self, key, key_manager_identifier).await
}
}
| 305 | 2,379 |
hyperswitch | crates/hyperswitch_domain_models/src/network_tokenization.rs | .rs | #[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
use cards::CardNumber;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use cards::{CardNumber, NetworkToken};
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub type NetworkTokenNumber = CardNumber;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub type NetworkTokenNumber = NetworkToken;
| 127 | 2,380 |
hyperswitch | crates/hyperswitch_domain_models/src/merchant_account.rs | .rs | use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
pii, type_name,
types::keymanager::{self},
};
use diesel_models::{
enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v1")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
primary_business_details: item.primary_business_details,
frm_routing_algorithm: item.frm_routing_algorithm,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v2")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
let MerchantAccountSetter {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
} = item;
Self {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
}
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
/// Get the organization_id from MerchantAccount
pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId {
&self.organization_id
}
}
#[cfg(feature = "v1")]
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
return_url: Option<String>,
webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
sub_merchants_enabled: Option<bool>,
parent_merchant_id: Option<common_utils::id_type::MerchantId>,
enable_payment_response_hash: Option<bool>,
payment_response_hash_key: Option<String>,
redirect_to_merchant_with_http_post: Option<bool>,
publishable_key: Option<String>,
locker_id: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
routing_algorithm: Option<serde_json::Value>,
primary_business_details: Option<serde_json::Value>,
intent_fulfillment_time: Option<i64>,
frm_routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
default_profile: Option<Option<common_utils::id_type::ProfileId>>,
payment_link_config: Option<serde_json::Value>,
pm_collect_link_config: Option<serde_json::Value>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
UnsetDefaultProfile,
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
publishable_key: Option<String>,
metadata: Option<Box<pii::SecretSerdeValue>>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
webhook_details,
return_url,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
frm_routing_algorithm,
webhook_details,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
modified_at: now,
intent_fulfillment_time,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
storage_scheme: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::UnsetDefaultProfile => Self {
default_profile: Some(None),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
publishable_key,
metadata,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
publishable_key,
metadata: metadata.map(|metadata| *metadata),
modified_at: now,
storage_scheme: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let id = self.get_id().to_owned();
let setter = diesel_models::merchant_account::MerchantAccountSetter {
id,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
metadata: self.metadata,
created_at: self.created_at,
modified_at: self.modified_at,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
publishable_key,
storage_scheme: item.storage_scheme,
metadata: item.metadata,
created_at: item.created_at,
modified_at: item.modified_at,
organization_id: item.organization_id,
recon_status: item.recon_status,
is_platform_account: item.is_platform_account,
version: item.version,
product_type: item.product_type,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: self.id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
publishable_key: Some(self.publishable_key),
metadata: self.metadata,
created_at: now,
modified_at: now,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
})
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let setter = diesel_models::merchant_account::MerchantAccountSetter {
merchant_id: self.merchant_id,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: self.created_at,
modified_at: self.modified_at,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: self.version,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let merchant_id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
frm_routing_algorithm: item.frm_routing_algorithm,
primary_business_details: item.primary_business_details,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: Some(self.merchant_id.clone()),
merchant_id: self.merchant_id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
return_url: self.return_url,
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
enable_payment_response_hash: Some(self.enable_payment_response_hash),
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: Some(self.redirect_to_merchant_with_http_post),
publishable_key: Some(self.publishable_key),
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: now,
modified_at: now,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
})
}
}
impl MerchantAccount {
pub fn get_compatible_connector(&self) -> Option<api_models::enums::Connector> {
let metadata: Option<api_models::admin::MerchantAccountMetadata> =
self.metadata.as_ref().and_then(|meta| {
meta.clone()
.parse_value("MerchantAccountMetadata")
.map_err(|err| logger::error!("Failed to deserialize {:?}", err))
.ok()
});
metadata.and_then(|a| a.compatible_connector)
}
}
| 6,402 | 2,381 |
hyperswitch | crates/hyperswitch_domain_models/src/router_flow_types.rs | .rs | pub mod access_token_auth;
pub mod authentication;
pub mod dispute;
pub mod files;
pub mod fraud_check;
pub mod mandate_revoke;
pub mod payments;
pub mod payouts;
pub mod refunds;
pub mod revenue_recovery;
pub mod unified_authentication_service;
pub mod webhooks;
pub use access_token_auth::*;
pub use dispute::*;
pub use files::*;
pub use fraud_check::*;
pub use payments::*;
pub use payouts::*;
pub use refunds::*;
pub use revenue_recovery::*;
pub use unified_authentication_service::*;
pub use webhooks::*;
| 104 | 2,382 |
hyperswitch | crates/hyperswitch_domain_models/src/type_encryption.rs | .rs | use async_trait::async_trait;
use common_utils::{
crypto,
encryption::Encryption,
errors::{self, CustomResult},
ext_traits::AsyncExt,
metrics::utils::record_operation_time,
types::keymanager::{Identifier, KeyManagerState},
};
use encrypt::TypeEncryption;
use masking::Secret;
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
mod encrypt {
use async_trait::async_trait;
use common_utils::{
crypto,
encryption::Encryption,
errors::{self, CustomResult},
ext_traits::ByteSliceExt,
keymanager::call_encryption_service,
transformers::{ForeignFrom, ForeignTryFrom},
types::keymanager::{
BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse,
DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, Identifier,
KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
},
};
use error_stack::ResultExt;
use http::Method;
use masking::{PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use rustc_hash::FxHashMap;
use super::{metrics, EncryptedJsonType};
#[async_trait]
pub trait TypeEncryption<
T,
V: crypto::EncodeMessage + crypto::DecodeMessage,
S: masking::Strategy<T>,
>: Sized
{
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<T, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn encrypt(
masked_data: Secret<T, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<T, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<T, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
}
fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool {
#[cfg(feature = "encryption_service")]
{
_state.enabled
}
#[cfg(not(feature = "encryption_service"))]
{
false
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<String> + Send + Sync,
> TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<String, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<String, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = encrypted_data.into_inner();
let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: String = std::str::from_utf8(&data)
.change_context(errors::CryptoError::DecodingFailed)?
.to_string();
Ok(Self::new(value.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<String, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<String, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(
v.clone(),
crypt_algo.encode_message(key, v.peek().as_bytes())?.into(),
),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
let data = crypt_algo.decode_message(key, v.clone().into_inner())?;
let value: String = std::str::from_utf8(&data)
.change_context(errors::CryptoError::DecodingFailed)?
.to_string();
Ok((k, Self::new(value.into(), v.into_inner())))
})
.collect()
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<serde_json::Value> + Send + Sync,
> TypeEncryption<serde_json::Value, V, S>
for crypto::Encryptable<Secret<serde_json::Value, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<serde_json::Value, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::EncodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<serde_json::Value, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let data = serde_json::to_vec(&masked_data.peek())
.change_context(errors::CryptoError::DecodingFailed)?;
let encrypted_data = crypt_algo.encode_message(key, &data)?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = encrypted_data.into_inner();
let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: serde_json::Value = serde_json::from_slice(&data)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(Self::new(value.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<serde_json::Value, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<serde_json::Value, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
let data = serde_json::to_vec(v.peek())
.change_context(errors::CryptoError::DecodingFailed)?;
Ok((
k,
Self::new(v, crypt_algo.encode_message(key, &data)?.into()),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?;
let value: serde_json::Value = serde_json::from_slice(&data)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok((k, Self::new(value.into(), v.into_inner())))
})
.collect()
}
}
impl<T> EncryptedJsonType<T>
where
T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned,
{
fn serialize_json_bytes(&self) -> CustomResult<Secret<Vec<u8>>, errors::CryptoError> {
common_utils::ext_traits::Encode::encode_to_vec(self.inner())
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to JSON serialize data before encryption")
.map(Secret::new)
}
fn deserialize_json_bytes<S>(
bytes: Secret<Vec<u8>>,
) -> CustomResult<Secret<Self, S>, errors::ParsingError>
where
S: masking::Strategy<Self>,
{
bytes
.peek()
.as_slice()
.parse_struct::<T>(std::any::type_name::<T>())
.map(|result| Secret::new(Self::from(result)))
.attach_printable("Failed to JSON deserialize data after decryption")
}
}
#[async_trait]
impl<
T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned + Send,
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<EncryptedJsonType<T>> + Send + Sync,
> TypeEncryption<EncryptedJsonType<T>, V, S>
for crypto::Encryptable<Secret<EncryptedJsonType<T>, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<EncryptedJsonType<T>, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?;
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::encrypt_via_api(state, data_bytes, identifier, key, crypt_algo)
.await?;
Ok(Self::new(masked_data, result.into_encrypted()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::decrypt_via_api(state, encrypted_data, identifier, key, crypt_algo)
.await?;
result
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<EncryptedJsonType<T>, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?;
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::encrypt(data_bytes, key, crypt_algo).await?;
Ok(Self::new(masked_data, result.into_encrypted()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::decrypt(encrypted_data, key, crypt_algo).await?;
result
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let hashmap_capacity = masked_data.len();
let data_bytes = masked_data.iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?;
map.insert(key.to_owned(), value_bytes);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_encrypt_via_api(
state, data_bytes, identifier, key, crypt_algo,
)
.await?;
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let original_value = masked_data
.get(&key)
.ok_or(errors::CryptoError::EncodingFailed)
.attach_printable_lazy(|| {
format!("Failed to find {key} in input hashmap")
})?;
map.insert(
key,
Self::new(original_value.clone(), value.into_encrypted()),
);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_decrypt_via_api(
state,
encrypted_data,
identifier,
key,
crypt_algo,
)
.await?;
let hashmap_capacity = result.len();
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let deserialized_value = value
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)?;
map.insert(key, deserialized_value);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let hashmap_capacity = masked_data.len();
let data_bytes = masked_data.iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?;
map.insert(key.to_owned(), value_bytes);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_encrypt(data_bytes, key, crypt_algo).await?;
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let original_value = masked_data
.get(&key)
.ok_or(errors::CryptoError::EncodingFailed)
.attach_printable_lazy(|| {
format!("Failed to find {key} in input hashmap")
})?;
map.insert(
key,
Self::new(original_value.clone(), value.into_encrypted()),
);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_decrypt(encrypted_data, key, crypt_algo).await?;
let hashmap_capacity = result.len();
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let deserialized_value = value
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)?;
map.insert(key, deserialized_value);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<Vec<u8>> + Send + Sync,
> TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<Vec<u8>, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<Vec<u8>, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = encrypted_data.into_inner();
let data = crypt_algo.decode_message(key, encrypted.clone())?;
Ok(Self::new(data.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<Vec<u8>, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(response) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<Vec<u8>, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(
crypt_algo
.decode_message(key, v.clone().into_inner().clone())?
.into(),
v.into_inner(),
),
))
})
.collect()
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EncryptedJsonType<T>(T);
impl<T> EncryptedJsonType<T> {
pub fn inner(&self) -> &T {
&self.0
}
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> From<T> for EncryptedJsonType<T> {
fn from(value: T) -> Self {
Self(value)
}
}
impl<T> std::ops::Deref for EncryptedJsonType<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner()
}
}
/// Type alias for `Option<Encryptable<Secret<EncryptedJsonType<T>>>>`
pub type OptionalEncryptableJsonType<T> = Option<crypto::Encryptable<Secret<EncryptedJsonType<T>>>>;
pub trait Lift<U> {
type SelfWrapper<T>;
type OtherWrapper<T, E>;
fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E>
where
Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>;
}
impl<U> Lift<U> for Option<U> {
type SelfWrapper<T> = Option<T>;
type OtherWrapper<T, E> = CustomResult<Option<T>, E>;
fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E>
where
Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>,
{
func(self)
}
}
#[async_trait]
pub trait AsyncLift<U> {
type SelfWrapper<T>;
type OtherWrapper<T, E>;
async fn async_lift<Func, F, E, V>(self, func: Func) -> Self::OtherWrapper<V, E>
where
Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync,
F: futures::Future<Output = Self::OtherWrapper<V, E>> + Send;
}
#[async_trait]
impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V {
type SelfWrapper<T> = <V as Lift<U>>::SelfWrapper<T>;
type OtherWrapper<T, E> = <V as Lift<U>>::OtherWrapper<T, E>;
async fn async_lift<Func, F, E, W>(self, func: Func) -> Self::OtherWrapper<W, E>
where
Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync,
F: futures::Future<Output = Self::OtherWrapper<W, E>> + Send,
{
func(self).await
}
}
#[inline]
async fn encrypt<E: Clone, S>(
state: &KeyManagerState,
inner: Secret<E, S>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<crypto::Encryptable<Secret<E, S>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
record_operation_time(
crypto::Encryptable::encrypt_via_api(state, inner, identifier, key, crypto::GcmAes256),
&metrics::ENCRYPTION_TIME,
&[],
)
.await
}
#[inline]
async fn batch_encrypt<E: Clone, S>(
state: &KeyManagerState,
inner: FxHashMap<String, Secret<E, S>>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
if !inner.is_empty() {
record_operation_time(
crypto::Encryptable::batch_encrypt_via_api(
state,
inner,
identifier,
key,
crypto::GcmAes256,
),
&metrics::ENCRYPTION_TIME,
&[],
)
.await
} else {
Ok(FxHashMap::default())
}
}
#[inline]
async fn encrypt_optional<E: Clone, S>(
state: &KeyManagerState,
inner: Option<Secret<E, S>>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
Secret<E, S>: Send,
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
inner
.async_map(|f| encrypt(state, f, identifier, key))
.await
.transpose()
}
#[inline]
async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Option<Encryption>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
inner
.async_map(|item| decrypt(state, item, identifier, key))
.await
.transpose()
}
#[inline]
async fn decrypt<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Encryption,
identifier: Identifier,
key: &[u8],
) -> CustomResult<crypto::Encryptable<Secret<T, S>>, CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
record_operation_time(
crypto::Encryptable::decrypt_via_api(state, inner, identifier, key, crypto::GcmAes256),
&metrics::DECRYPTION_TIME,
&[],
)
.await
}
#[inline]
async fn batch_decrypt<E: Clone, S>(
state: &KeyManagerState,
inner: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
if !inner.is_empty() {
record_operation_time(
crypto::Encryptable::batch_decrypt_via_api(
state,
inner,
identifier,
key,
crypto::GcmAes256,
),
&metrics::ENCRYPTION_TIME,
&[],
)
.await
} else {
Ok(FxHashMap::default())
}
}
pub enum CryptoOperation<T: Clone, S: masking::Strategy<T>> {
Encrypt(Secret<T, S>),
EncryptOptional(Option<Secret<T, S>>),
Decrypt(Encryption),
DecryptOptional(Option<Encryption>),
BatchEncrypt(FxHashMap<String, Secret<T, S>>),
BatchDecrypt(FxHashMap<String, Encryption>),
}
use errors::CryptoError;
#[derive(router_derive::TryGetEnumVariant)]
#[error(CryptoError::EncodingFailed)]
pub enum CryptoOutput<T: Clone, S: masking::Strategy<T>> {
Operation(crypto::Encryptable<Secret<T, S>>),
OptionalOperation(Option<crypto::Encryptable<Secret<T, S>>>),
BatchOperation(FxHashMap<String, crypto::Encryptable<Secret<T, S>>>),
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all, fields(table = table_name))]
pub async fn crypto_operation<T: Clone + Send, S: masking::Strategy<T>>(
state: &KeyManagerState,
table_name: &str,
operation: CryptoOperation<T, S>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<CryptoOutput<T, S>, CryptoError>
where
Secret<T, S>: Send,
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
match operation {
CryptoOperation::Encrypt(data) => {
let data = encrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::Operation(data))
}
CryptoOperation::EncryptOptional(data) => {
let data = encrypt_optional(state, data, identifier, key).await?;
Ok(CryptoOutput::OptionalOperation(data))
}
CryptoOperation::Decrypt(data) => {
let data = decrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::Operation(data))
}
CryptoOperation::DecryptOptional(data) => {
let data = decrypt_optional(state, data, identifier, key).await?;
Ok(CryptoOutput::OptionalOperation(data))
}
CryptoOperation::BatchEncrypt(data) => {
let data = batch_encrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::BatchOperation(data))
}
CryptoOperation::BatchDecrypt(data) => {
let data = batch_decrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::BatchOperation(data))
}
}
}
pub(crate) mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64, once_cell};
global_meter!(GLOBAL_METER, "ROUTER_API");
// Encryption and Decryption metrics
histogram_metric_f64!(ENCRYPTION_TIME, GLOBAL_METER);
histogram_metric_f64!(DECRYPTION_TIME, GLOBAL_METER);
counter_metric!(ENCRYPTION_API_FAILURES, GLOBAL_METER);
counter_metric!(DECRYPTION_API_FAILURES, GLOBAL_METER);
counter_metric!(APPLICATION_ENCRYPTION_COUNT, GLOBAL_METER);
counter_metric!(APPLICATION_DECRYPTION_COUNT, GLOBAL_METER);
}
| 10,781 | 2,383 |
hyperswitch | crates/hyperswitch_domain_models/src/disputes.rs | .rs | use crate::errors;
pub struct DisputeListConstraints {
pub dispute_id: Option<String>,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub limit: Option<u32>,
pub offset: Option<u32>,
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub dispute_status: Option<Vec<common_enums::DisputeStatus>>,
pub dispute_stage: Option<Vec<common_enums::DisputeStage>>,
pub reason: Option<String>,
pub connector: Option<Vec<String>>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub currency: Option<Vec<common_enums::Currency>>,
pub time_range: Option<common_utils::types::TimeRange>,
}
impl
TryFrom<(
api_models::disputes::DisputeListGetConstraints,
Option<Vec<common_utils::id_type::ProfileId>>,
)> for DisputeListConstraints
{
type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
fn try_from(
(value, auth_profile_id_list): (
api_models::disputes::DisputeListGetConstraints,
Option<Vec<common_utils::id_type::ProfileId>>,
),
) -> Result<Self, Self::Error> {
let api_models::disputes::DisputeListGetConstraints {
dispute_id,
payment_id,
limit,
offset,
profile_id,
dispute_status,
dispute_stage,
reason,
connector,
merchant_connector_id,
currency,
time_range,
} = value;
let profile_id_from_request_body = profile_id;
// Match both the profile ID from the request body and the list of authenticated profile IDs coming from auth layer
let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
(None, None) => None,
// Case when the request body profile ID is None, but authenticated profile IDs are available, return the auth list
(None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
// Case when the request body profile ID is provided, but the auth list is None, create a vector with the request body profile ID
(Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
(Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
// Check if the profile ID from the request body is present in the authenticated profile ID list
let profile_id_from_request_body_is_available_in_auth_profile_id_list =
auth_profile_id_list.contains(&profile_id_from_request_body);
if profile_id_from_request_body_is_available_in_auth_profile_id_list {
Some(vec![profile_id_from_request_body])
} else {
// If the profile ID is not valid, return an error indicating access is not available
return Err(error_stack::Report::new(
errors::api_error_response::ApiErrorResponse::PreconditionFailed {
message: format!(
"Access not available for the given profile_id {:?}",
profile_id_from_request_body
),
},
));
}
}
};
Ok(Self {
dispute_id,
payment_id,
limit,
offset,
profile_id: profile_id_list,
dispute_status,
dispute_stage,
reason,
connector,
merchant_connector_id,
currency,
time_range,
})
}
}
| 731 | 2,384 |
hyperswitch | crates/hyperswitch_domain_models/src/api.rs | .rs | use std::{collections::HashSet, fmt::Display};
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
impl_api_event_type,
};
use super::payment_method_data::PaymentMethodData;
#[derive(Debug, Eq, PartialEq)]
pub enum ApplicationResponse<R> {
Json(R),
StatusOk,
TextPlain(String),
JsonForRedirection(api_models::payments::RedirectionResponse),
Form(Box<RedirectionFormData>),
PaymentLinkForm(Box<PaymentLinkAction>),
FileData((Vec<u8>, mime::Mime)),
JsonWithHeaders((R, Vec<(String, masking::Maskable<String>)>)),
GenericLinkForm(Box<GenericLinks>),
}
impl<R> ApplicationResponse<R> {
/// Get the json response from response
#[inline]
pub fn get_json_body(
self,
) -> common_utils::errors::CustomResult<R, common_utils::errors::ValidationError> {
match self {
Self::Json(body) | Self::JsonWithHeaders((body, _)) => Ok(body),
Self::TextPlain(_)
| Self::JsonForRedirection(_)
| Self::Form(_)
| Self::PaymentLinkForm(_)
| Self::FileData(_)
| Self::GenericLinkForm(_)
| Self::StatusOk => Err(common_utils::errors::ValidationError::InvalidValue {
message: "expected either Json or JsonWithHeaders Response".to_string(),
}
.into()),
}
}
}
impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self {
Self::Json(r) => r.get_api_event_type(),
Self::JsonWithHeaders((r, _)) => r.get_api_event_type(),
_ => None,
}
}
}
impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, GenericLinkFormData));
#[derive(Debug, Eq, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: crate::router_response_types::RedirectForm,
pub payment_method_data: Option<PaymentMethodData>,
pub amount: String,
pub currency: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentLinkAction {
PaymentLinkFormData(PaymentLinkFormData),
PaymentLinkStatus(PaymentLinkStatusData),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkFormData {
pub js_script: String,
pub css_script: String,
pub sdk_url: String,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkStatusData {
pub js_script: String,
pub css_script: String,
}
#[derive(Debug, Eq, PartialEq)]
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum GenericLinksData {
ExpiredLink(GenericExpiredLinkData),
PaymentMethodCollect(GenericLinkFormData),
PayoutLink(GenericLinkFormData),
PayoutLinkStatus(GenericLinkStatusData),
PaymentMethodCollectStatus(GenericLinkStatusData),
SecurePaymentLink(PaymentLinkFormData),
}
impl Display for GenericLinksData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match *self {
Self::ExpiredLink(_) => "ExpiredLink",
Self::PaymentMethodCollect(_) => "PaymentMethodCollect",
Self::PayoutLink(_) => "PayoutLink",
Self::PayoutLinkStatus(_) => "PayoutLinkStatus",
Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus",
Self::SecurePaymentLink(_) => "SecurePaymentLink",
}
)
}
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericExpiredLinkData {
pub title: String,
pub message: String,
pub theme: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkFormData {
pub js_data: String,
pub css_data: String,
pub sdk_url: String,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkStatusData {
pub js_data: String,
pub css_data: String,
}
| 977 | 2,385 |
hyperswitch | crates/hyperswitch_domain_models/src/bulk_tokenization.rs | .rs | use api_models::{payment_methods as payment_methods_api, payments as payments_api};
use cards::CardNumber;
use common_enums as enums;
use common_utils::{
errors,
ext_traits::OptionExt,
id_type, pii,
transformers::{ForeignFrom, ForeignTryFrom},
};
use error_stack::report;
use crate::{
address::{Address, AddressDetails, PhoneDetails},
router_request_types::CustomerDetails,
};
#[derive(Debug)]
pub struct CardNetworkTokenizeRequest {
pub data: TokenizeDataRequest,
pub customer: CustomerDetails,
pub billing: Option<Address>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_issuer: Option<String>,
}
#[derive(Debug)]
pub enum TokenizeDataRequest {
Card(TokenizeCardRequest),
ExistingPaymentMethod(TokenizePaymentMethodRequest),
}
#[derive(Clone, Debug)]
pub struct TokenizeCardRequest {
pub raw_card_number: CardNumber,
pub card_expiry_month: masking::Secret<String>,
pub card_expiry_year: masking::Secret<String>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
}
#[derive(Clone, Debug)]
pub struct TokenizePaymentMethodRequest {
pub payment_method_id: String,
pub card_cvc: Option<masking::Secret<String>>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct CardNetworkTokenizeRecord {
// Card details
pub raw_card_number: Option<CardNumber>,
pub card_expiry_month: Option<masking::Secret<String>>,
pub card_expiry_year: Option<masking::Secret<String>>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
// Payment method details
pub payment_method_id: Option<String>,
pub payment_method_type: Option<payment_methods_api::CardType>,
pub payment_method_issuer: Option<String>,
// Customer details
pub customer_id: id_type::CustomerId,
#[serde(rename = "name")]
pub customer_name: Option<masking::Secret<String>>,
#[serde(rename = "email")]
pub customer_email: Option<pii::Email>,
#[serde(rename = "phone")]
pub customer_phone: Option<masking::Secret<String>>,
#[serde(rename = "phone_country_code")]
pub customer_phone_country_code: Option<String>,
// Billing details
pub billing_address_city: Option<String>,
pub billing_address_country: Option<enums::CountryAlpha2>,
pub billing_address_line1: Option<masking::Secret<String>>,
pub billing_address_line2: Option<masking::Secret<String>>,
pub billing_address_line3: Option<masking::Secret<String>>,
pub billing_address_zip: Option<masking::Secret<String>>,
pub billing_address_state: Option<masking::Secret<String>>,
pub billing_address_first_name: Option<masking::Secret<String>>,
pub billing_address_last_name: Option<masking::Secret<String>>,
pub billing_phone_number: Option<masking::Secret<String>>,
pub billing_phone_country_code: Option<String>,
pub billing_email: Option<pii::Email>,
// Other details
pub line_number: Option<u64>,
pub merchant_id: Option<id_type::MerchantId>,
}
impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails {
fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self {
Self {
id: record.customer_id.clone(),
name: record.customer_name.clone(),
email: record.customer_email.clone(),
phone: record.customer_phone.clone(),
phone_country_code: record.customer_phone_country_code.clone(),
}
}
}
impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::Address {
fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self {
Self {
address: Some(payments_api::AddressDetails {
first_name: record.billing_address_first_name.clone(),
last_name: record.billing_address_last_name.clone(),
line1: record.billing_address_line1.clone(),
line2: record.billing_address_line2.clone(),
line3: record.billing_address_line3.clone(),
city: record.billing_address_city.clone(),
zip: record.billing_address_zip.clone(),
state: record.billing_address_state.clone(),
country: record.billing_address_country,
}),
phone: Some(payments_api::PhoneDetails {
number: record.billing_phone_number.clone(),
country_code: record.billing_phone_country_code.clone(),
}),
email: record.billing_email.clone(),
}
}
}
impl ForeignTryFrom<CardNetworkTokenizeRecord> for payment_methods_api::CardNetworkTokenizeRequest {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(record: CardNetworkTokenizeRecord) -> Result<Self, Self::Error> {
let billing = Some(payments_api::Address::foreign_from(&record));
let customer = payments_api::CustomerDetails::foreign_from(&record);
let merchant_id = record.merchant_id.get_required_value("merchant_id")?;
match (
record.raw_card_number,
record.card_expiry_month,
record.card_expiry_year,
record.payment_method_id,
) {
(Some(raw_card_number), Some(card_expiry_month), Some(card_expiry_year), None) => {
Ok(Self {
merchant_id,
data: payment_methods_api::TokenizeDataRequest::Card(
payment_methods_api::TokenizeCardRequest {
raw_card_number,
card_expiry_month,
card_expiry_year,
card_cvc: record.card_cvc,
card_holder_name: record.card_holder_name,
nick_name: record.nick_name,
card_issuing_country: record.card_issuing_country,
card_network: record.card_network,
card_issuer: record.card_issuer,
card_type: record.card_type.clone(),
},
),
billing,
customer,
metadata: None,
payment_method_issuer: record.payment_method_issuer,
})
}
(None, None, None, Some(payment_method_id)) => Ok(Self {
merchant_id,
data: payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(
payment_methods_api::TokenizePaymentMethodRequest {
payment_method_id,
card_cvc: record.card_cvc,
},
),
billing,
customer,
metadata: None,
payment_method_issuer: record.payment_method_issuer,
}),
_ => Err(report!(errors::ValidationError::InvalidValue {
message: "Invalid record in bulk tokenization - expected one of card details or payment method details".to_string()
})),
}
}
}
impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetail {
fn foreign_from(card: &TokenizeCardRequest) -> Self {
Self {
card_number: masking::Secret::new(card.raw_card_number.get_card_no()),
card_exp_month: card.card_expiry_month.clone(),
card_exp_year: card.card_expiry_year.clone(),
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_issuing_country: card.card_issuing_country.clone(),
card_network: card.card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card
.card_type
.as_ref()
.map(|card_type| card_type.to_string()),
}
}
}
impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(customer: CustomerDetails) -> Result<Self, Self::Error> {
Ok(Self {
id: customer.customer_id.get_required_value("customer_id")?,
name: customer.name,
email: customer.email,
phone: customer.phone,
phone_country_code: customer.phone_country_code,
})
}
}
impl ForeignFrom<payment_methods_api::CardNetworkTokenizeRequest> for CardNetworkTokenizeRequest {
fn foreign_from(req: payment_methods_api::CardNetworkTokenizeRequest) -> Self {
Self {
data: TokenizeDataRequest::foreign_from(req.data),
customer: CustomerDetails::foreign_from(req.customer),
billing: req.billing.map(ForeignFrom::foreign_from),
metadata: req.metadata,
payment_method_issuer: req.payment_method_issuer,
}
}
}
impl ForeignFrom<payment_methods_api::TokenizeDataRequest> for TokenizeDataRequest {
fn foreign_from(req: payment_methods_api::TokenizeDataRequest) -> Self {
match req {
payment_methods_api::TokenizeDataRequest::Card(card) => {
Self::Card(TokenizeCardRequest {
raw_card_number: card.raw_card_number,
card_expiry_month: card.card_expiry_month,
card_expiry_year: card.card_expiry_year,
card_cvc: card.card_cvc,
card_holder_name: card.card_holder_name,
nick_name: card.nick_name,
card_issuing_country: card.card_issuing_country,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_type: card.card_type,
})
}
payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(pm) => {
Self::ExistingPaymentMethod(TokenizePaymentMethodRequest {
payment_method_id: pm.payment_method_id,
card_cvc: pm.card_cvc,
})
}
}
}
}
impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails {
fn foreign_from(req: payments_api::CustomerDetails) -> Self {
Self {
customer_id: Some(req.id),
name: req.name,
email: req.email,
phone: req.phone,
phone_country_code: req.phone_country_code,
}
}
}
impl ForeignFrom<payments_api::Address> for Address {
fn foreign_from(req: payments_api::Address) -> Self {
Self {
address: req.address.map(ForeignFrom::foreign_from),
phone: req.phone.map(ForeignFrom::foreign_from),
email: req.email,
}
}
}
impl ForeignFrom<payments_api::AddressDetails> for AddressDetails {
fn foreign_from(req: payments_api::AddressDetails) -> Self {
Self {
city: req.city,
country: req.country,
line1: req.line1,
line2: req.line2,
line3: req.line3,
zip: req.zip,
state: req.state,
first_name: req.first_name,
last_name: req.last_name,
}
}
}
impl ForeignFrom<payments_api::PhoneDetails> for PhoneDetails {
fn foreign_from(req: payments_api::PhoneDetails) -> Self {
Self {
number: req.number,
country_code: req.country_code,
}
}
}
| 2,443 | 2,386 |
hyperswitch | crates/hyperswitch_domain_models/src/relay.rs | .rs | use common_enums::enums;
use common_utils::{
self,
errors::{CustomResult, ValidationError},
id_type::{self, GenerateId},
pii,
types::{keymanager, MinorUnit},
};
use diesel_models::relay::RelayUpdateInternal;
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{router_data::ErrorResponse, router_response_types};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Relay {
pub id: id_type::RelayId,
pub connector_resource_id: String,
pub connector_id: id_type::MerchantConnectorAccountId,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
pub relay_type: enums::RelayType,
pub request_data: Option<RelayData>,
pub status: enums::RelayStatus,
pub connector_reference_id: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub response_data: Option<pii::SecretSerdeValue>,
}
impl Relay {
pub fn new(
relay_request: &api_models::relay::RelayRequest,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> Self {
let relay_id = id_type::RelayId::generate();
Self {
id: relay_id.clone(),
connector_resource_id: relay_request.connector_resource_id.clone(),
connector_id: relay_request.connector_id.clone(),
profile_id: profile_id.clone(),
merchant_id: merchant_id.clone(),
relay_type: common_enums::RelayType::Refund,
request_data: relay_request.data.clone().map(From::from),
status: common_enums::RelayStatus::Created,
connector_reference_id: None,
error_code: None,
error_message: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
response_data: None,
}
}
}
impl From<api_models::relay::RelayData> for RelayData {
fn from(relay: api_models::relay::RelayData) -> Self {
match relay {
api_models::relay::RelayData::Refund(relay_refund_request) => {
Self::Refund(RelayRefundData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
}
}
}
impl From<api_models::relay::RelayRefundRequestData> for RelayRefundData {
fn from(relay: api_models::relay::RelayRefundRequestData) -> Self {
Self {
amount: relay.amount,
currency: relay.currency,
reason: relay.reason,
}
}
}
impl RelayUpdate {
pub fn from(
response: Result<router_response_types::RefundsResponseData, ErrorResponse>,
) -> Self {
match response {
Err(error) => Self::ErrorUpdate {
error_code: error.code,
error_message: error.reason.unwrap_or(error.message),
status: common_enums::RelayStatus::Failure,
},
Ok(response) => Self::StatusUpdate {
connector_reference_id: Some(response.connector_refund_id),
status: common_enums::RelayStatus::from(response.refund_status),
},
}
}
}
impl From<RelayData> for api_models::relay::RelayData {
fn from(relay: RelayData) -> Self {
match relay {
RelayData::Refund(relay_refund_request) => {
Self::Refund(api_models::relay::RelayRefundRequestData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
}
}
}
impl From<Relay> for api_models::relay::RelayResponse {
fn from(value: Relay) -> Self {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data = value.request_data.map(|relay_data| match relay_data {
RelayData::Refund(relay_refund_request) => {
api_models::relay::RelayData::Refund(api_models::relay::RelayRefundRequestData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
});
Self {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data,
connector_reference_id: value.connector_reference_id,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", untagged)]
pub enum RelayData {
Refund(RelayRefundData),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RelayRefundData {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub reason: Option<String>,
}
#[derive(Debug)]
pub enum RelayUpdate {
ErrorUpdate {
error_code: String,
error_message: String,
status: enums::RelayStatus,
},
StatusUpdate {
connector_reference_id: Option<String>,
status: common_enums::RelayStatus,
},
}
impl From<RelayUpdate> for RelayUpdateInternal {
fn from(value: RelayUpdate) -> Self {
match value {
RelayUpdate::ErrorUpdate {
error_code,
error_message,
status,
} => Self {
error_code: Some(error_code),
error_message: Some(error_message),
connector_reference_id: None,
status: Some(status),
modified_at: common_utils::date_time::now(),
},
RelayUpdate::StatusUpdate {
connector_reference_id,
status,
} => Self {
connector_reference_id,
status: Some(status),
error_code: None,
error_message: None,
modified_at: common_utils::date_time::now(),
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Relay {
type DstType = diesel_models::relay::Relay;
type NewDstType = diesel_models::relay::RelayNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::relay::Relay {
id: self.id,
connector_resource_id: self.connector_resource_id,
connector_id: self.connector_id,
profile_id: self.profile_id,
merchant_id: self.merchant_id,
relay_type: self.relay_type,
request_data: self
.request_data
.map(|data| {
serde_json::to_value(data).change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
})
.transpose()?
.map(Secret::new),
status: self.status,
connector_reference_id: self.connector_reference_id,
error_code: self.error_code,
error_message: self.error_message,
created_at: self.created_at,
modified_at: self.modified_at,
response_data: self.response_data,
})
}
async fn convert_back(
_state: &keymanager::KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError> {
Ok(Self {
id: item.id,
connector_resource_id: item.connector_resource_id,
connector_id: item.connector_id,
profile_id: item.profile_id,
merchant_id: item.merchant_id,
relay_type: enums::RelayType::Refund,
request_data: item
.request_data
.map(|data| {
serde_json::from_value(data.expose()).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
},
)
})
.transpose()?,
status: item.status,
connector_reference_id: item.connector_reference_id,
error_code: item.error_code,
error_message: item.error_message,
created_at: item.created_at,
modified_at: item.modified_at,
response_data: item.response_data,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::relay::RelayNew {
id: self.id,
connector_resource_id: self.connector_resource_id,
connector_id: self.connector_id,
profile_id: self.profile_id,
merchant_id: self.merchant_id,
relay_type: self.relay_type,
request_data: self
.request_data
.map(|data| {
serde_json::to_value(data).change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
})
.transpose()?
.map(Secret::new),
status: self.status,
connector_reference_id: self.connector_reference_id,
error_code: self.error_code,
error_message: self.error_message,
created_at: self.created_at,
modified_at: self.modified_at,
response_data: self.response_data,
})
}
}
| 2,125 | 2,387 |
hyperswitch | crates/hyperswitch_domain_models/src/router_data.rs | .rs | use std::{collections::HashMap, marker::PhantomData};
use common_types::primitive_wrappers;
use common_utils::{
errors::IntegrityCheckError,
ext_traits::{OptionExt, ValueExt},
id_type,
types::MinorUnit,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use crate::{
network_tokenization::NetworkTokenNumber, payment_address::PaymentAddress, payment_method_data,
payments,
};
#[cfg(feature = "v2")]
use crate::{
payments::{
payment_attempt::{ErrorDetails, PaymentAttemptUpdate},
payment_intent::PaymentIntentUpdate,
},
router_flow_types, router_request_types, router_response_types,
};
#[derive(Debug, Clone)]
pub struct RouterData<Flow, Request, Response> {
pub flow: PhantomData<Flow>,
pub merchant_id: id_type::MerchantId,
pub customer_id: Option<id_type::CustomerId>,
pub connector_customer: Option<String>,
pub connector: String,
// TODO: This should be a PaymentId type.
// Make this change after all the connector dependency has been removed from connectors
pub payment_id: String,
pub attempt_id: String,
pub tenant_id: id_type::TenantId,
pub status: common_enums::enums::AttemptStatus,
pub payment_method: common_enums::enums::PaymentMethod,
pub connector_auth_type: ConnectorAuthType,
pub description: Option<String>,
pub address: PaymentAddress,
pub auth_type: common_enums::enums::AuthenticationType,
pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
pub access_token: Option<AccessToken>,
pub session_token: Option<String>,
pub reference_id: Option<String>,
pub payment_method_token: Option<PaymentMethodToken>,
pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
pub preprocessing_id: Option<String>,
/// This is the balance amount for gift cards or voucher
pub payment_method_balance: Option<PaymentMethodBalance>,
///for switching between two different versions of the same connector
pub connector_api_version: Option<String>,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: Request,
/// Contains flow-specific data that the connector responds with.
pub response: Result<Response, ErrorResponse>,
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
#[cfg(feature = "payouts")]
/// Contains payout method data
pub payout_method_data: Option<api_models::payouts::PayoutMethodData>,
#[cfg(feature = "payouts")]
/// Contains payout's quote ID
pub quote_id: Option<String>,
pub test_mode: Option<bool>,
pub connector_http_status_code: Option<u16>,
pub external_latency: Option<u128>,
/// Contains apple pay flow type simplified or manual
pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>,
pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>,
pub dispute_id: Option<String>,
pub refund_id: Option<String>,
/// This field is used to store various data regarding the response from connector
pub connector_response: Option<ConnectorResponseData>,
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
pub integrity_check: Result<(), IntegrityCheckError>,
pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>,
pub header_payload: Option<payments::HeaderPayload>,
pub connector_mandate_request_reference_id: Option<String>,
pub authentication_id: Option<String>,
/// Contains the type of sca exemption required for the transaction
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
}
// 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::enums::Currency, common_utils::pii::SecretSerdeValue>,
},
CertificateAuth {
certificate: Secret<String>,
private_key: Secret<String>,
},
#[default]
NoKey,
}
impl ConnectorAuthType {
pub fn from_option_secret_value(
value: Option<common_utils::pii::SecretSerdeValue>,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
pub fn from_secret_value(
value: common_utils::pii::SecretSerdeValue,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
// show only first and last two digits of the key and mask others with *
// mask the entire key if it's length is less than or equal to 4
fn mask_key(&self, key: String) -> Secret<String> {
let key_len = key.len();
let masked_key = if key_len <= 4 {
"*".repeat(key_len)
} else {
// Show the first two and last two characters, mask the rest with '*'
let mut masked_key = String::new();
let key_len = key.len();
// Iterate through characters by their index
for (index, character) in key.chars().enumerate() {
if index < 2 || index >= key_len - 2 {
masked_key.push(character); // Keep the first two and last two characters
} else {
masked_key.push('*'); // Mask the middle characters
}
}
masked_key
};
Secret::new(masked_key)
}
// Mask the keys in the auth_type
pub fn get_masked_keys(&self) -> Self {
match self {
Self::TemporaryAuth => Self::TemporaryAuth,
Self::NoKey => Self::NoKey,
Self::HeaderKey { api_key } => Self::HeaderKey {
api_key: self.mask_key(api_key.clone().expose()),
},
Self::BodyKey { api_key, key1 } => Self::BodyKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
},
Self::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
},
Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
key2: self.mask_key(key2.clone().expose()),
},
Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey {
auth_key_map: auth_key_map.clone(),
},
Self::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate: self.mask_key(certificate.clone().expose()),
private_key: self.mask_key(private_key.clone().expose()),
},
}
}
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct AccessToken {
pub token: Secret<String>,
pub expires: i64,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<ApplePayPredecryptData>),
GooglePayDecrypt(Box<GooglePayDecryptedData>),
PazeDecrypt(Box<PazeDecryptedData>),
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPredecryptData {
pub application_primary_account_number: Secret<String>,
pub application_expiration_date: String,
pub currency_code: String,
pub transaction_amount: i64,
pub device_manufacturer_identifier: Secret<String>,
pub payment_data_type: Secret<String>,
pub payment_data: ApplePayCryptogramData,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayCryptogramData {
pub online_payment_cryptogram: Secret<String>,
pub eci_indicator: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayDecryptedData {
pub message_expiration: String,
pub message_id: String,
#[serde(rename = "paymentMethod")]
pub payment_method_type: String,
pub payment_method_details: GooglePayPaymentMethodDetails,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentMethodDetails {
pub auth_method: common_enums::enums::GooglePayAuthMethod,
pub expiration_month: cards::CardExpirationMonth,
pub expiration_year: cards::CardExpirationYear,
pub pan: cards::CardNumber,
pub cryptogram: Option<Secret<String>>,
pub eci_indicator: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDecryptedData {
pub client_id: Secret<String>,
pub profile_id: String,
pub token: PazeToken,
pub payment_card_network: common_enums::enums::CardNetwork,
pub dynamic_data: Vec<PazeDynamicData>,
pub billing_address: PazeAddress,
pub consumer: PazeConsumer,
pub eci: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeToken {
pub payment_token: NetworkTokenNumber,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
pub payment_account_reference: Secret<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub dynamic_data_expiration: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeAddress {
pub name: Option<Secret<String>>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub city: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeConsumer {
// This is consumer data not customer data.
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub full_name: Secret<String>,
pub email_address: common_utils::pii::Email,
pub mobile_number: Option<PazePhoneNumber>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
pub language_code: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazePhoneNumber {
pub country_code: Secret<String>,
pub phone_number: Secret<String>,
}
#[derive(Debug, Default, Clone)]
pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::enums::Currency>,
pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct PaymentMethodBalance {
pub amount: MinorUnit,
pub currency: common_enums::enums::Currency,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorResponseData {
pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
}
impl ConnectorResponseData {
pub fn with_additional_payment_method_data(
additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> Self {
Self {
additional_payment_method_data: Some(additional_payment_method_data),
extended_authorization_response_data: None,
}
}
pub fn get_extended_authorization_response_data(
&self,
) -> Option<&ExtendedAuthorizationResponseData> {
self.extended_authorization_response_data.as_ref()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum AdditionalPaymentMethodConnectorResponse {
Card {
/// Details regarding the authentication details of the connector, if this is a 3ds payment.
authentication_data: Option<serde_json::Value>,
/// Various payment checks that are done for a payment
payment_checks: Option<serde_json::Value>,
/// Card Network returned by the processor
card_network: Option<String>,
/// Domestic(Co-Branded) Card network returned by the processor
domestic_network: Option<String>,
},
PayLater {
klarna_sdk: Option<KlarnaSdkResponse>,
},
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExtendedAuthorizationResponseData {
pub extended_authentication_applied:
Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KlarnaSdkResponse {
pub payment_type: Option<String>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
pub attempt_status: Option<common_enums::enums::AttemptStatus>,
pub connector_transaction_id: Option<String>,
pub network_decline_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_message: Option<String>,
}
impl Default for ErrorResponse {
fn default() -> Self {
Self {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}
}
}
impl ErrorResponse {
pub 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(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}
}
}
/// Get updatable trakcer objects of payment intent and payment attempt
#[cfg(feature = "v2")]
pub trait TrackerPostUpdateObjects<Flow, FlowRequest, D> {
fn get_payment_intent_update(
&self,
payment_data: &D,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate;
fn get_payment_attempt_update(
&self,
payment_data: &D,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate;
/// Get the amount that can be captured for the payment
fn get_amount_capturable(&self, payment_data: &D) -> Option<MinorUnit>;
/// Get the amount that has been captured for the payment
fn get_captured_amount(&self, payment_data: &D) -> Option<MinorUnit>;
/// Get the attempt status based on parameters like captured amount and amount capturable
fn get_attempt_status_for_db_update(
&self,
payment_data: &D,
) -> common_enums::enums::AttemptStatus;
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::Authorize,
router_request_types::PaymentsAuthorizeData,
payments::PaymentConfirmData<router_flow_types::Authorize>,
>
for RouterData<
router_flow_types::Authorize,
router_request_types::PaymentsAuthorizeData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
let status = payment_data.payment_attempt.status.is_terminal_status();
let updated_feature_metadata =
payment_data
.payment_intent
.feature_metadata
.clone()
.map(|mut feature_metadata| {
if let Some(ref mut payment_revenue_recovery_metadata) =
feature_metadata.payment_revenue_recovery_metadata
{
payment_revenue_recovery_metadata.payment_connector_transmission = if self
.response
.is_ok()
{
common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded
} else {
common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful
};
}
Box::new(feature_metadata)
});
match self.response {
Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: common_enums::IntentStatus::from(
self.get_attempt_status_for_db_update(payment_data),
),
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: updated_feature_metadata,
},
Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: error
.attempt_status
.map(common_enums::IntentStatus::from)
.unwrap_or(common_enums::IntentStatus::Failed),
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: updated_feature_metadata,
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
connector_metadata,
network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
} => {
let attempt_status = self.get_attempt_status_for_db_update(payment_data);
let connector_payment_id = match resource_id {
router_request_types::ResponseId::NoResponseId => None,
router_request_types::ResponseId::ConnectorTransactionId(id)
| router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),
};
PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(
payments::payment_attempt::ConfirmIntentResponseUpdate {
status: attempt_status,
connector_payment_id,
updated_by: storage_scheme.to_string(),
redirection_data: *redirection_data.clone(),
amount_capturable,
connector_metadata: connector_metadata.clone().map(Secret::new),
connector_token_details: response_router_data
.get_updated_connector_token_details(
payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| {
token_details.get_connector_token_request_reference_id()
}),
),
},
))
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionUpdateResponse { .. } => {
todo!()
}
},
Err(ref error_response) => {
let ErrorResponse {
code,
message,
reason,
status_code: _,
attempt_status,
connector_transaction_id,
network_decline_code,
network_advice_code,
network_error_message,
} = error_response.clone();
let attempt_status = attempt_status.unwrap_or(self.status);
let error_details = ErrorDetails {
code,
message,
reason,
unified_code: None,
unified_message: None,
network_advice_code,
network_decline_code,
network_error_message,
};
PaymentAttemptUpdate::ErrorUpdate {
status: attempt_status,
error: error_details,
amount_capturable,
connector_payment_id: connector_transaction_id,
updated_by: storage_scheme.to_string(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
_payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
) -> common_enums::AttemptStatus {
// For this step, consider whatever status was given by the connector module
// We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount
self.status
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is already succeeded / failed we cannot capture any more amount
// So set the amount capturable to zero
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Cancelled => Some(MinorUnit::zero()),
// For these statuses, update the capturable amount when it reaches terminal / capturable state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
// If status is requires capture, get the total amount that can be captured
// This is in cases where the capture method will be `manual` or `manual_multiple`
// We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow, after doing authorization this state is invalid
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount that was captured
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is succeeded then we have captured the whole amount
// we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported
common_enums::IntentStatus::Succeeded => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// No amount is captured
common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Failed => {
Some(MinorUnit::zero())
}
// For these statuses, update the amount captured when it reaches terminal state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
// No amount has been captured yet
common_enums::IntentStatus::RequiresCapture => Some(MinorUnit::zero()),
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::Capture,
router_request_types::PaymentsCaptureData,
payments::PaymentCaptureData<router_flow_types::Capture>,
>
for RouterData<
router_flow_types::Capture,
router_request_types::PaymentsCaptureData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
match self.response {
Ok(ref _response) => PaymentIntentUpdate::CaptureUpdate {
status: common_enums::IntentStatus::from(
self.get_attempt_status_for_db_update(payment_data),
),
amount_captured,
updated_by: storage_scheme.to_string(),
},
Err(ref error) => PaymentIntentUpdate::CaptureUpdate {
status: error
.attempt_status
.map(common_enums::IntentStatus::from)
.unwrap_or(common_enums::IntentStatus::Failed),
amount_captured,
updated_by: storage_scheme.to_string(),
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
connector_metadata,
network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
} => {
let attempt_status = self.status;
PaymentAttemptUpdate::CaptureUpdate {
status: attempt_status,
amount_capturable,
updated_by: storage_scheme.to_string(),
}
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionUpdateResponse { .. } => {
todo!()
}
},
Err(ref error_response) => {
let ErrorResponse {
code,
message,
reason,
status_code: _,
attempt_status,
connector_transaction_id,
network_advice_code,
network_decline_code,
network_error_message,
} = error_response.clone();
let attempt_status = attempt_status.unwrap_or(self.status);
let error_details = ErrorDetails {
code,
message,
reason,
unified_code: None,
unified_message: None,
network_advice_code,
network_decline_code,
network_error_message,
};
PaymentAttemptUpdate::ErrorUpdate {
status: attempt_status,
error: error_details,
amount_capturable,
connector_payment_id: connector_transaction_id,
updated_by: storage_scheme.to_string(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
) -> common_enums::AttemptStatus {
match self.status {
common_enums::AttemptStatus::Charged => {
let amount_captured = self
.get_captured_amount(payment_data)
.unwrap_or(MinorUnit::zero());
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
if amount_captured == total_amount {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::PartialCharged
}
}
_ => self.status,
}
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is already succeeded / failed we cannot capture any more amount
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Cancelled => Some(MinorUnit::zero()),
// For these statuses, update the capturable amount when it reaches terminal / capturable state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is succeeded then we have captured the whole amount
common_enums::IntentStatus::Succeeded => {
let amount_to_capture = payment_data
.payment_attempt
.amount_details
.get_amount_to_capture();
let amount_captured = amount_to_capture
.unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount());
Some(amount_captured)
}
// No amount is captured
common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Failed => {
Some(MinorUnit::zero())
}
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// For these statuses, update the amount captured when it reaches terminal state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => {
todo!()
}
}
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::PSync,
router_request_types::PaymentsSyncData,
payments::PaymentStatusData<router_flow_types::PSync>,
>
for RouterData<
router_flow_types::PSync,
router_request_types::PaymentsSyncData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
match self.response {
Ok(ref _response) => PaymentIntentUpdate::SyncUpdate {
status: common_enums::IntentStatus::from(
self.get_attempt_status_for_db_update(payment_data),
),
amount_captured,
updated_by: storage_scheme.to_string(),
},
Err(ref error) => PaymentIntentUpdate::SyncUpdate {
status: error
.attempt_status
.map(common_enums::IntentStatus::from)
.unwrap_or(common_enums::IntentStatus::Failed),
amount_captured,
updated_by: storage_scheme.to_string(),
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
connector_metadata,
network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
} => {
let attempt_status = self.get_attempt_status_for_db_update(payment_data);
PaymentAttemptUpdate::SyncUpdate {
status: attempt_status,
amount_capturable,
updated_by: storage_scheme.to_string(),
}
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionUpdateResponse { .. } => {
todo!()
}
},
Err(ref error_response) => {
let ErrorResponse {
code,
message,
reason,
status_code: _,
attempt_status,
connector_transaction_id,
network_advice_code,
network_decline_code,
network_error_message,
} = error_response.clone();
let attempt_status = attempt_status.unwrap_or(common_enums::AttemptStatus::Failure);
let error_details = ErrorDetails {
code,
message,
reason,
unified_code: None,
unified_message: None,
network_advice_code,
network_decline_code,
network_error_message,
};
PaymentAttemptUpdate::ErrorUpdate {
status: attempt_status,
error: error_details,
amount_capturable,
connector_payment_id: connector_transaction_id,
updated_by: storage_scheme.to_string(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
) -> common_enums::AttemptStatus {
match self.status {
common_enums::AttemptStatus::Charged => {
let amount_captured = self
.get_captured_amount(payment_data)
.unwrap_or(MinorUnit::zero());
let total_amount = payment_data
.payment_attempt
.as_ref()
.map(|attempt| attempt.amount_details.get_net_amount())
.unwrap_or(MinorUnit::zero());
if amount_captured == total_amount {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::PartialCharged
}
}
_ => self.status,
}
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
) -> Option<MinorUnit> {
let payment_attempt = payment_data.payment_attempt.as_ref()?;
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is already succeeded / failed we cannot capture any more amount
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Cancelled => Some(MinorUnit::zero()),
// For these statuses, update the capturable amount when it reaches terminal / capturable state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
) -> Option<MinorUnit> {
let payment_attempt = payment_data.payment_attempt.as_ref()?;
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is succeeded then we have captured the whole amount or amount_to_capture
common_enums::IntentStatus::Succeeded => {
let amount_to_capture = payment_attempt.amount_details.get_amount_to_capture();
let amount_captured =
amount_to_capture.unwrap_or(payment_attempt.amount_details.get_net_amount());
Some(amount_captured)
}
// No amount is captured
common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Failed => {
Some(MinorUnit::zero())
}
// For these statuses, update the amount captured when it reaches terminal state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::SetupMandate,
router_request_types::SetupMandateRequestData,
payments::PaymentConfirmData<router_flow_types::SetupMandate>,
>
for RouterData<
router_flow_types::SetupMandate,
router_request_types::SetupMandateRequestData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
match self.response {
Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: common_enums::IntentStatus::from(
self.get_attempt_status_for_db_update(payment_data),
),
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: None,
},
Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: error
.attempt_status
.map(common_enums::IntentStatus::from)
.unwrap_or(common_enums::IntentStatus::Failed),
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: None,
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
connector_metadata,
network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
} => {
let attempt_status = self.get_attempt_status_for_db_update(payment_data);
let connector_payment_id = match resource_id {
router_request_types::ResponseId::NoResponseId => None,
router_request_types::ResponseId::ConnectorTransactionId(id)
| router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),
};
PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(
payments::payment_attempt::ConfirmIntentResponseUpdate {
status: attempt_status,
connector_payment_id,
updated_by: storage_scheme.to_string(),
redirection_data: *redirection_data.clone(),
amount_capturable,
connector_metadata: connector_metadata.clone().map(Secret::new),
connector_token_details: response_router_data
.get_updated_connector_token_details(
payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| {
token_details.get_connector_token_request_reference_id()
}),
),
},
))
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionUpdateResponse { .. } => {
todo!()
}
},
Err(ref error_response) => {
let ErrorResponse {
code,
message,
reason,
status_code: _,
attempt_status,
connector_transaction_id,
network_advice_code,
network_decline_code,
network_error_message,
} = error_response.clone();
let attempt_status = attempt_status.unwrap_or(self.status);
let error_details = ErrorDetails {
code,
message,
reason,
unified_code: None,
unified_message: None,
network_advice_code,
network_decline_code,
network_error_message,
};
PaymentAttemptUpdate::ErrorUpdate {
status: attempt_status,
error: error_details,
amount_capturable,
connector_payment_id: connector_transaction_id,
updated_by: storage_scheme.to_string(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
_payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
) -> common_enums::AttemptStatus {
// For this step, consider whatever status was given by the connector module
// We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount
self.status
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is already succeeded / failed we cannot capture any more amount
// So set the amount capturable to zero
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Cancelled => Some(MinorUnit::zero()),
// For these statuses, update the capturable amount when it reaches terminal / capturable state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
// If status is requires capture, get the total amount that can be captured
// This is in cases where the capture method will be `manual` or `manual_multiple`
// We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow, after doing authorization this state is invalid
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount that was captured
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is succeeded then we have captured the whole amount
// we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported
common_enums::IntentStatus::Succeeded => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// No amount is captured
common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Failed => {
Some(MinorUnit::zero())
}
// For these statuses, update the amount captured when it reaches terminal state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
// No amount has been captured yet
common_enums::IntentStatus::RequiresCapture => Some(MinorUnit::zero()),
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
}
| 11,087 | 2,388 |
hyperswitch | crates/hyperswitch_domain_models/src/payment_method_data.rs | .rs | use api_models::{
mandates,
payment_methods::{self},
payments::{
additional_info as payment_additional_types, AmazonPayRedirectData, ExtendedCardInfo,
},
};
use common_enums::enums as api_enums;
#[cfg(feature = "v2")]
use common_utils::ext_traits::OptionExt;
use common_utils::{
id_type,
new_type::{
MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId,
},
pii::{self, Email},
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::Date;
// We need to derive Serialize and Deserialize because some parts of payment method data are being
// stored in the database as serde_json::Value
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum PaymentMethodData {
Card(Card),
CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId),
CardRedirect(CardRedirectData),
Wallet(WalletData),
PayLater(PayLaterData),
BankRedirect(BankRedirectData),
BankDebit(BankDebitData),
BankTransfer(Box<BankTransferData>),
Crypto(CryptoData),
MandatePayment,
Reward,
RealTimePayment(Box<RealTimePaymentData>),
Upi(UpiData),
Voucher(VoucherData),
GiftCard(Box<GiftCardData>),
CardToken(CardToken),
OpenBanking(OpenBankingData),
NetworkToken(NetworkTokenData),
MobilePayment(MobilePaymentData),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplePayFlow {
Simplified(api_models::payments::PaymentProcessingDetails),
Manual,
}
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
Self::Card(_) | Self::NetworkToken(_) | Self::CardDetailsForNetworkTransactionId(_) => {
Some(common_enums::PaymentMethod::Card)
}
Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
Self::Reward => Some(common_enums::PaymentMethod::Reward),
Self::RealTimePayment(_) => Some(common_enums::PaymentMethod::RealTimePayment),
Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking),
Self::MobilePayment(_) => Some(common_enums::PaymentMethod::MobilePayment),
Self::CardToken(_) | Self::MandatePayment => None,
}
}
pub fn is_network_token_payment_method_data(&self) -> bool {
matches!(self, Self::NetworkToken(_))
}
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct Card {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_cvc: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetailsForNetworkTransactionId {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetail {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
}
impl CardDetailsForNetworkTransactionId {
pub fn get_nti_and_card_details_for_mit_flow(
recurring_details: mandates::RecurringDetails,
) -> Option<(api_models::payments::MandateReferenceId, Self)> {
let network_transaction_id_and_card_details = match recurring_details {
mandates::RecurringDetails::NetworkTransactionIdAndCardDetails(
network_transaction_id_and_card_details,
) => Some(network_transaction_id_and_card_details),
mandates::RecurringDetails::MandateId(_)
| mandates::RecurringDetails::PaymentMethodId(_)
| mandates::RecurringDetails::ProcessorPaymentToken(_) => None,
}?;
let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(
network_transaction_id_and_card_details
.network_transaction_id
.peek()
.to_string(),
);
Some((
mandate_reference_id,
network_transaction_id_and_card_details.clone().into(),
))
}
}
impl From<&Card> for CardDetail {
fn from(item: &Card) -> Self {
Self {
card_number: item.card_number.to_owned(),
card_exp_month: item.card_exp_month.to_owned(),
card_exp_year: item.card_exp_year.to_owned(),
card_issuer: item.card_issuer.to_owned(),
card_network: item.card_network.to_owned(),
card_type: item.card_type.to_owned(),
card_issuing_country: item.card_issuing_country.to_owned(),
bank_code: item.bank_code.to_owned(),
nick_name: item.nick_name.to_owned(),
card_holder_name: item.card_holder_name.to_owned(),
}
}
}
impl From<mandates::NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId {
fn from(card_details_for_nti: mandates::NetworkTransactionIdAndCardDetails) -> Self {
Self {
card_number: card_details_for_nti.card_number,
card_exp_month: card_details_for_nti.card_exp_month,
card_exp_year: card_details_for_nti.card_exp_year,
card_issuer: card_details_for_nti.card_issuer,
card_network: card_details_for_nti.card_network,
card_type: card_details_for_nti.card_type,
card_issuing_country: card_details_for_nti.card_issuing_country,
bank_code: card_details_for_nti.bank_code,
nick_name: card_details_for_nti.nick_name,
card_holder_name: card_details_for_nti.card_holder_name,
}
}
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum CardRedirectData {
Knet {},
Benefit {},
MomoAtm {},
CardRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum PayLaterData {
KlarnaRedirect {},
KlarnaSdk { token: String },
AffirmRedirect {},
AfterpayClearpayRedirect {},
PayBrightRedirect {},
WalleyRedirect {},
AlmaRedirect {},
AtomeRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum WalletData {
AliPayQr(Box<AliPayQr>),
AliPayRedirect(AliPayRedirection),
AliPayHkRedirect(AliPayHkRedirection),
AmazonPayRedirect(Box<AmazonPayRedirectData>),
MomoRedirect(MomoRedirection),
KakaoPayRedirect(KakaoPayRedirection),
GoPayRedirect(GoPayRedirection),
GcashRedirect(GcashRedirection),
ApplePay(ApplePayWalletData),
ApplePayRedirect(Box<ApplePayRedirectData>),
ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
DanaRedirect {},
GooglePay(GooglePayWalletData),
GooglePayRedirect(Box<GooglePayRedirectData>),
GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
MbWayRedirect(Box<MbWayRedirection>),
MobilePayRedirect(Box<MobilePayRedirection>),
PaypalRedirect(PaypalRedirection),
PaypalSdk(PayPalWalletData),
Paze(PazeWalletData),
SamsungPay(Box<SamsungPayWalletData>),
TwintRedirect {},
VippsRedirect {},
TouchNGoRedirect(Box<TouchNGoRedirection>),
WeChatPayRedirect(Box<WeChatPayRedirection>),
WeChatPayQr(Box<WeChatPayQr>),
CashappQr(Box<CashappQr>),
SwishQr(SwishQrData),
Mifinity(MifinityData),
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MifinityData {
pub date_of_birth: Secret<Date>,
pub language_preference: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct PazeWalletData {
pub complete_response: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
pub payment_credential: SamsungPayWalletCredentials,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletCredentials {
pub method: Option<String>,
pub recurring_payment: Option<bool>,
pub card_brand: common_enums::SamsungPayCardBrand,
pub dpan_last_four_digits: Option<String>,
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
#[serde(rename = "3_d_s")]
pub token_data: SamsungPayTokenData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayTokenData {
#[serde(rename = "type")]
pub three_ds_type: Option<String>,
pub version: String,
pub data: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayWalletData {
/// The type of payment method
pub pm_type: String,
/// User-facing message to describe the payment method that funds this transaction.
pub description: String,
/// The information of the payment method
pub info: GooglePayPaymentMethodInfo,
/// The tokenization data of Google pay
pub tokenization_data: GpayTokenizationData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayThirdPartySdkData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayThirdPartySdkData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPay {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CashappQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaypalRedirection {
/// paypal's email address
pub email: Option<Email>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayHkRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MomoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct KakaoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GcashRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MobilePayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MbWayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayPaymentMethodInfo {
/// The name of the card network
pub card_network: String,
/// The details of the card
pub card_details: String,
//assurance_details of the card
pub assurance_details: Option<GooglePayAssuranceDetails>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct GooglePayAssuranceDetails {
///indicates that Cardholder possession validation has been performed
pub card_holder_authenticated: bool,
/// indicates that identification and verifications (ID&V) was performed
pub account_verified: bool,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PayPalWalletData {
/// Token generated for the Apple pay
pub token: String,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct TouchNGoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SwishQrData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GpayTokenizationData {
/// The type of the token
pub token_type: String,
/// Token generated for the wallet
pub token: String,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayWalletData {
/// The payment data of Apple pay
pub payment_data: String,
/// The payment method of Apple pay
pub payment_method: ApplepayPaymentMethod,
/// The unique identifier for the transaction
pub transaction_identifier: String,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplepayPaymentMethod {
pub display_name: String,
pub network: String,
pub pm_type: String,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum RealTimePaymentData {
DuitNow {},
Fps {},
PromptPay {},
VietQr {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum BankRedirectData {
BancontactCard {
card_number: Option<cards::CardNumber>,
card_exp_month: Option<Secret<String>>,
card_exp_year: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
},
Bizum {},
Blik {
blik_code: Option<String>,
},
Eps {
bank_name: Option<common_enums::BankNames>,
country: Option<api_enums::CountryAlpha2>,
},
Giropay {
bank_account_bic: Option<Secret<String>>,
bank_account_iban: Option<Secret<String>>,
country: Option<api_enums::CountryAlpha2>,
},
Ideal {
bank_name: Option<common_enums::BankNames>,
},
Interac {
country: Option<api_enums::CountryAlpha2>,
email: Option<Email>,
},
OnlineBankingCzechRepublic {
issuer: common_enums::BankNames,
},
OnlineBankingFinland {
email: Option<Email>,
},
OnlineBankingPoland {
issuer: common_enums::BankNames,
},
OnlineBankingSlovakia {
issuer: common_enums::BankNames,
},
OpenBankingUk {
issuer: Option<common_enums::BankNames>,
country: Option<api_enums::CountryAlpha2>,
},
Przelewy24 {
bank_name: Option<common_enums::BankNames>,
},
Sofort {
country: Option<api_enums::CountryAlpha2>,
preferred_language: Option<String>,
},
Trustly {
country: Option<api_enums::CountryAlpha2>,
},
OnlineBankingFpx {
issuer: common_enums::BankNames,
},
OnlineBankingThailand {
issuer: common_enums::BankNames,
},
LocalBankRedirect {},
Eft {
provider: String,
},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenBankingData {
OpenBankingPIS {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct CryptoData {
pub pay_currency: Option<String>,
pub network: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiData {
UpiCollect(UpiCollectData),
UpiIntent(UpiIntentData),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiCollectData {
pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiIntentData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VoucherData {
Boleto(Box<BoletoVoucherData>),
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart(Box<AlfamartVoucherData>),
Indomaret(Box<IndomaretVoucherData>),
Oxxo,
SevenEleven(Box<JCSVoucherData>),
Lawson(Box<JCSVoucherData>),
MiniStop(Box<JCSVoucherData>),
FamilyMart(Box<JCSVoucherData>),
Seicomart(Box<JCSVoucherData>),
PayEasy(Box<JCSVoucherData>),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BoletoVoucherData {
/// The shopper's social security number
pub social_security_number: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AlfamartVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct IndomaretVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct JCSVoucherData {}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum GiftCardData {
Givex(GiftCardDetails),
PaySafeCard {},
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct GiftCardDetails {
/// The gift card number
pub number: Secret<String>,
/// The card verification code.
pub cvc: Secret<String>,
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
#[serde(rename_all = "snake_case")]
pub struct CardToken {
/// The card holder's name
pub card_holder_name: Option<Secret<String>>,
/// The CVC number for the card
pub card_cvc: Option<Secret<String>>,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BankDebitData {
AchBankDebit {
account_number: Secret<String>,
routing_number: Secret<String>,
card_holder_name: Option<Secret<String>>,
bank_account_holder_name: Option<Secret<String>>,
bank_name: Option<common_enums::BankNames>,
bank_type: Option<common_enums::BankType>,
bank_holder_type: Option<common_enums::BankHolderType>,
},
SepaBankDebit {
iban: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
BecsBankDebit {
account_number: Secret<String>,
bsb_number: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
BacsBankDebit {
account_number: Secret<String>,
sort_code: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BankTransferData {
AchBankTransfer {},
SepaBankTransfer {},
BacsBankTransfer {},
MultibancoBankTransfer {},
PermataBankTransfer {},
BcaBankTransfer {},
BniVaBankTransfer {},
BriVaBankTransfer {},
CimbVaBankTransfer {},
DanamonVaBankTransfer {},
MandiriVaBankTransfer {},
Pix {
/// Unique key for pix transfer
pix_key: Option<Secret<String>>,
/// CPF is a Brazilian tax identification number
cpf: Option<Secret<String>>,
/// CNPJ is a Brazilian company tax identification number
cnpj: Option<Secret<String>>,
},
Pse {},
LocalBankTransfer {
bank_code: Option<String>,
},
InstantBankTransfer {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct SepaAndBacsBillingDetails {
/// The Email ID for SEPA and BACS billing
pub email: Email,
/// The billing name for SEPA and BACS billing
pub name: Secret<String>,
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenData {
pub token_number: cards::CardNumber,
pub token_exp_month: Secret<String>,
pub token_exp_year: Secret<String>,
pub token_cryptogram: Option<Secret<String>>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub eci: Option<String>,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenData {
pub network_token: cards::NetworkToken,
pub network_token_exp_month: Secret<String>,
pub network_token_exp_year: Secret<String>,
pub cryptogram: Option<Secret<String>>,
pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<payment_methods::CardType>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub card_holder_name: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub eci: Option<String>,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenDetails {
pub network_token: cards::NetworkToken,
pub network_token_exp_month: Secret<String>,
pub network_token_exp_year: Secret<String>,
pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<payment_methods::CardType>,
pub card_issuing_country: Option<api_enums::CountryAlpha2>,
pub card_holder_name: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MobilePaymentData {
DirectCarrierBilling {
/// The phone number of the user
msisdn: String,
/// Unique user identifier
client_uid: Option<String>,
},
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData {
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn try_from(value: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> {
match value {
payment_methods::PaymentMethodCreateData::Card(payment_methods::CardDetail {
card_number,
card_exp_month,
card_exp_year,
card_cvc,
card_issuer,
card_network,
card_type,
card_issuing_country,
nick_name,
card_holder_name,
}) => Ok(Self::Card(Card {
card_number,
card_exp_month,
card_exp_year,
card_cvc: card_cvc.get_required_value("card_cvc")?,
card_issuer,
card_network,
card_type: card_type.map(|card_type| card_type.to_string()),
card_issuing_country: card_issuing_country.map(|country| country.to_string()),
bank_code: None,
nick_name,
card_holder_name,
})),
}
}
}
impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
match api_model_payment_method_data {
api_models::payments::PaymentMethodData::Card(card_data) => {
Self::Card(Card::from(card_data))
}
api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {
Self::CardRedirect(From::from(card_redirect))
}
api_models::payments::PaymentMethodData::Wallet(wallet_data) => {
Self::Wallet(From::from(wallet_data))
}
api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {
Self::PayLater(From::from(pay_later_data))
}
api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
Self::BankRedirect(From::from(bank_redirect_data))
}
api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
Self::BankDebit(From::from(bank_debit_data))
}
api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))
}
api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
Self::Crypto(From::from(crypto_data))
}
api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
api_models::payments::PaymentMethodData::Reward => Self::Reward,
api_models::payments::PaymentMethodData::RealTimePayment(real_time_payment_data) => {
Self::RealTimePayment(Box::new(From::from(*real_time_payment_data)))
}
api_models::payments::PaymentMethodData::Upi(upi_data) => {
Self::Upi(From::from(upi_data))
}
api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
Self::Voucher(From::from(voucher_data))
}
api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
Self::GiftCard(Box::new(From::from(*gift_card)))
}
api_models::payments::PaymentMethodData::CardToken(card_token) => {
Self::CardToken(From::from(card_token))
}
api_models::payments::PaymentMethodData::OpenBanking(ob_data) => {
Self::OpenBanking(From::from(ob_data))
}
api_models::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => {
Self::MobilePayment(From::from(mobile_payment_data))
}
}
}
}
impl From<api_models::payments::Card> for Card {
fn from(value: api_models::payments::Card) -> Self {
let api_models::payments::Card {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
card_cvc,
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code,
nick_name,
} = value;
Self {
card_number,
card_exp_month,
card_exp_year,
card_cvc,
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code,
nick_name,
card_holder_name,
}
}
}
impl From<api_models::payments::CardRedirectData> for CardRedirectData {
fn from(value: api_models::payments::CardRedirectData) -> Self {
match value {
api_models::payments::CardRedirectData::Knet {} => Self::Knet {},
api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},
api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},
api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},
}
}
}
impl From<CardRedirectData> for api_models::payments::CardRedirectData {
fn from(value: CardRedirectData) -> Self {
match value {
CardRedirectData::Knet {} => Self::Knet {},
CardRedirectData::Benefit {} => Self::Benefit {},
CardRedirectData::MomoAtm {} => Self::MomoAtm {},
CardRedirectData::CardRedirect {} => Self::CardRedirect {},
}
}
}
impl From<api_models::payments::WalletData> for WalletData {
fn from(value: api_models::payments::WalletData) -> Self {
match value {
api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),
api_models::payments::WalletData::AliPayRedirect(_) => {
Self::AliPayRedirect(AliPayRedirection {})
}
api_models::payments::WalletData::AliPayHkRedirect(_) => {
Self::AliPayHkRedirect(AliPayHkRedirection {})
}
api_models::payments::WalletData::AmazonPayRedirect(_) => {
Self::AmazonPayRedirect(Box::new(AmazonPayRedirectData {}))
}
api_models::payments::WalletData::MomoRedirect(_) => {
Self::MomoRedirect(MomoRedirection {})
}
api_models::payments::WalletData::KakaoPayRedirect(_) => {
Self::KakaoPayRedirect(KakaoPayRedirection {})
}
api_models::payments::WalletData::GoPayRedirect(_) => {
Self::GoPayRedirect(GoPayRedirection {})
}
api_models::payments::WalletData::GcashRedirect(_) => {
Self::GcashRedirect(GcashRedirection {})
}
api_models::payments::WalletData::ApplePay(apple_pay_data) => {
Self::ApplePay(ApplePayWalletData::from(apple_pay_data))
}
api_models::payments::WalletData::ApplePayRedirect(_) => {
Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))
}
api_models::payments::WalletData::ApplePayThirdPartySdk(_) => {
Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {}))
}
api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},
api_models::payments::WalletData::GooglePay(google_pay_data) => {
Self::GooglePay(GooglePayWalletData::from(google_pay_data))
}
api_models::payments::WalletData::GooglePayRedirect(_) => {
Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))
}
api_models::payments::WalletData::GooglePayThirdPartySdk(_) => {
Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {}))
}
api_models::payments::WalletData::MbWayRedirect(..) => {
Self::MbWayRedirect(Box::new(MbWayRedirection {}))
}
api_models::payments::WalletData::MobilePayRedirect(_) => {
Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))
}
api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {
Self::PaypalRedirect(PaypalRedirection {
email: paypal_redirect_data.email,
})
}
api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {
Self::PaypalSdk(PayPalWalletData {
token: paypal_sdk_data.token,
})
}
api_models::payments::WalletData::Paze(paze_data) => {
Self::Paze(PazeWalletData::from(paze_data))
}
api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data)))
}
api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
api_models::payments::WalletData::TouchNGoRedirect(_) => {
Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))
}
api_models::payments::WalletData::WeChatPayRedirect(_) => {
Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))
}
api_models::payments::WalletData::WeChatPayQr(_) => {
Self::WeChatPayQr(Box::new(WeChatPayQr {}))
}
api_models::payments::WalletData::CashappQr(_) => {
Self::CashappQr(Box::new(CashappQr {}))
}
api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),
api_models::payments::WalletData::Mifinity(mifinity_data) => {
Self::Mifinity(MifinityData {
date_of_birth: mifinity_data.date_of_birth,
language_preference: mifinity_data.language_preference,
})
}
}
}
}
impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData {
fn from(value: api_models::payments::GooglePayWalletData) -> Self {
Self {
pm_type: value.pm_type,
description: value.description,
info: GooglePayPaymentMethodInfo {
card_network: value.info.card_network,
card_details: value.info.card_details,
assurance_details: value.info.assurance_details.map(|info| {
GooglePayAssuranceDetails {
card_holder_authenticated: info.card_holder_authenticated,
account_verified: info.account_verified,
}
}),
},
tokenization_data: GpayTokenizationData {
token_type: value.tokenization_data.token_type,
token: value.tokenization_data.token,
},
}
}
}
impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
fn from(value: api_models::payments::ApplePayWalletData) -> Self {
Self {
payment_data: value.payment_data,
payment_method: ApplepayPaymentMethod {
display_name: value.payment_method.display_name,
network: value.payment_method.network,
pm_type: value.payment_method.pm_type,
},
transaction_identifier: value.transaction_identifier,
}
}
}
impl From<api_models::payments::SamsungPayTokenData> for SamsungPayTokenData {
fn from(samsung_pay_token_data: api_models::payments::SamsungPayTokenData) -> Self {
Self {
three_ds_type: samsung_pay_token_data.three_ds_type,
version: samsung_pay_token_data.version,
data: samsung_pay_token_data.data,
}
}
}
impl From<api_models::payments::PazeWalletData> for PazeWalletData {
fn from(value: api_models::payments::PazeWalletData) -> Self {
Self {
complete_response: value.complete_response,
}
}
}
impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData {
fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self {
match value.payment_credential {
api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForApp(
samsung_pay_app_wallet_data,
) => Self {
payment_credential: SamsungPayWalletCredentials {
method: samsung_pay_app_wallet_data.method,
recurring_payment: samsung_pay_app_wallet_data.recurring_payment,
card_brand: samsung_pay_app_wallet_data.payment_card_brand.into(),
dpan_last_four_digits: samsung_pay_app_wallet_data.payment_last4_dpan,
card_last_four_digits: samsung_pay_app_wallet_data.payment_last4_fpan,
token_data: samsung_pay_app_wallet_data.token_data.into(),
},
},
api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForWeb(
samsung_pay_web_wallet_data,
) => Self {
payment_credential: SamsungPayWalletCredentials {
method: samsung_pay_web_wallet_data.method,
recurring_payment: samsung_pay_web_wallet_data.recurring_payment,
card_brand: samsung_pay_web_wallet_data.card_brand.into(),
dpan_last_four_digits: None,
card_last_four_digits: samsung_pay_web_wallet_data.card_last_four_digits,
token_data: samsung_pay_web_wallet_data.token_data.into(),
},
},
}
}
}
impl From<api_models::payments::PayLaterData> for PayLaterData {
fn from(value: api_models::payments::PayLaterData) -> Self {
match value {
api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect {}
}
api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},
api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},
api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},
api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},
}
}
}
impl From<api_models::payments::BankRedirectData> for BankRedirectData {
fn from(value: api_models::payments::BankRedirectData) -> Self {
match value {
api_models::payments::BankRedirectData::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
..
} => Self::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
},
api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
api_models::payments::BankRedirectData::Eps {
bank_name, country, ..
} => Self::Eps { bank_name, country },
api_models::payments::BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
country,
..
} => Self::Giropay {
bank_account_bic,
bank_account_iban,
country,
},
api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
Self::Ideal { bank_name }
}
api_models::payments::BankRedirectData::Interac { country, email } => {
Self::Interac { country, email }
}
api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
Self::OnlineBankingCzechRepublic { issuer }
}
api_models::payments::BankRedirectData::OnlineBankingFinland { email } => {
Self::OnlineBankingFinland { email }
}
api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
Self::OnlineBankingPoland { issuer }
}
api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
Self::OnlineBankingSlovakia { issuer }
}
api_models::payments::BankRedirectData::OpenBankingUk {
country, issuer, ..
} => Self::OpenBankingUk { country, issuer },
api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
Self::Przelewy24 { bank_name }
}
api_models::payments::BankRedirectData::Sofort {
preferred_language,
country,
..
} => Self::Sofort {
country,
preferred_language,
},
api_models::payments::BankRedirectData::Trustly { country } => Self::Trustly {
country: Some(country),
},
api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
Self::OnlineBankingFpx { issuer }
}
api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
Self::OnlineBankingThailand { issuer }
}
api_models::payments::BankRedirectData::LocalBankRedirect { .. } => {
Self::LocalBankRedirect {}
}
api_models::payments::BankRedirectData::Eft { provider } => Self::Eft { provider },
}
}
}
impl From<api_models::payments::CryptoData> for CryptoData {
fn from(value: api_models::payments::CryptoData) -> Self {
let api_models::payments::CryptoData {
pay_currency,
network,
} = value;
Self {
pay_currency,
network,
}
}
}
impl From<CryptoData> for api_models::payments::CryptoData {
fn from(value: CryptoData) -> Self {
let CryptoData {
pay_currency,
network,
} = value;
Self {
pay_currency,
network,
}
}
}
impl From<api_models::payments::UpiData> for UpiData {
fn from(value: api_models::payments::UpiData) -> Self {
match value {
api_models::payments::UpiData::UpiCollect(upi) => {
Self::UpiCollect(UpiCollectData { vpa_id: upi.vpa_id })
}
api_models::payments::UpiData::UpiIntent(_) => Self::UpiIntent(UpiIntentData {}),
}
}
}
impl From<UpiData> for api_models::payments::additional_info::UpiAdditionalData {
fn from(value: UpiData) -> Self {
match value {
UpiData::UpiCollect(upi) => Self::UpiCollect(Box::new(
payment_additional_types::UpiCollectAdditionalData {
vpa_id: upi.vpa_id.map(MaskedUpiVpaId::from),
},
)),
UpiData::UpiIntent(_) => {
Self::UpiIntent(Box::new(api_models::payments::UpiIntentData {}))
}
}
}
}
impl From<api_models::payments::VoucherData> for VoucherData {
fn from(value: api_models::payments::VoucherData) -> Self {
match value {
api_models::payments::VoucherData::Boleto(boleto_data) => {
Self::Boleto(Box::new(BoletoVoucherData {
social_security_number: boleto_data.social_security_number,
}))
}
api_models::payments::VoucherData::Alfamart(_) => {
Self::Alfamart(Box::new(AlfamartVoucherData {}))
}
api_models::payments::VoucherData::Indomaret(_) => {
Self::Indomaret(Box::new(IndomaretVoucherData {}))
}
api_models::payments::VoucherData::SevenEleven(_)
| api_models::payments::VoucherData::Lawson(_)
| api_models::payments::VoucherData::MiniStop(_)
| api_models::payments::VoucherData::FamilyMart(_)
| api_models::payments::VoucherData::Seicomart(_)
| api_models::payments::VoucherData::PayEasy(_) => {
Self::SevenEleven(Box::new(JCSVoucherData {}))
}
api_models::payments::VoucherData::Efecty => Self::Efecty,
api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
api_models::payments::VoucherData::RedCompra => Self::RedCompra,
api_models::payments::VoucherData::RedPagos => Self::RedPagos,
api_models::payments::VoucherData::Oxxo => Self::Oxxo,
}
}
}
impl From<Box<BoletoVoucherData>> for Box<api_models::payments::BoletoVoucherData> {
fn from(value: Box<BoletoVoucherData>) -> Self {
Self::new(api_models::payments::BoletoVoucherData {
social_security_number: value.social_security_number,
})
}
}
impl From<Box<AlfamartVoucherData>> for Box<api_models::payments::AlfamartVoucherData> {
fn from(_value: Box<AlfamartVoucherData>) -> Self {
Self::new(api_models::payments::AlfamartVoucherData {
first_name: None,
last_name: None,
email: None,
})
}
}
impl From<Box<IndomaretVoucherData>> for Box<api_models::payments::IndomaretVoucherData> {
fn from(_value: Box<IndomaretVoucherData>) -> Self {
Self::new(api_models::payments::IndomaretVoucherData {
first_name: None,
last_name: None,
email: None,
})
}
}
impl From<Box<JCSVoucherData>> for Box<api_models::payments::JCSVoucherData> {
fn from(_value: Box<JCSVoucherData>) -> Self {
Self::new(api_models::payments::JCSVoucherData {
first_name: None,
last_name: None,
email: None,
phone_number: None,
})
}
}
impl From<VoucherData> for api_models::payments::VoucherData {
fn from(value: VoucherData) -> Self {
match value {
VoucherData::Boleto(boleto_data) => Self::Boleto(boleto_data.into()),
VoucherData::Alfamart(alfa_mart) => Self::Alfamart(alfa_mart.into()),
VoucherData::Indomaret(info_maret) => Self::Indomaret(info_maret.into()),
VoucherData::SevenEleven(jcs_data)
| VoucherData::Lawson(jcs_data)
| VoucherData::MiniStop(jcs_data)
| VoucherData::FamilyMart(jcs_data)
| VoucherData::Seicomart(jcs_data)
| VoucherData::PayEasy(jcs_data) => Self::SevenEleven(jcs_data.into()),
VoucherData::Efecty => Self::Efecty,
VoucherData::PagoEfectivo => Self::PagoEfectivo,
VoucherData::RedCompra => Self::RedCompra,
VoucherData::RedPagos => Self::RedPagos,
VoucherData::Oxxo => Self::Oxxo,
}
}
}
impl From<api_models::payments::GiftCardData> for GiftCardData {
fn from(value: api_models::payments::GiftCardData) -> Self {
match value {
api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
number: details.number,
cvc: details.cvc,
}),
api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
}
}
}
impl From<GiftCardData> for payment_additional_types::GiftCardAdditionalData {
fn from(value: GiftCardData) -> Self {
match value {
GiftCardData::Givex(details) => Self::Givex(Box::new(
payment_additional_types::GivexGiftCardAdditionalData {
last4: details
.number
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>()
.into(),
},
)),
GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
}
}
}
impl From<api_models::payments::CardToken> for CardToken {
fn from(value: api_models::payments::CardToken) -> Self {
let api_models::payments::CardToken {
card_holder_name,
card_cvc,
} = value;
Self {
card_holder_name,
card_cvc,
}
}
}
impl From<CardToken> for payment_additional_types::CardTokenAdditionalData {
fn from(value: CardToken) -> Self {
let CardToken {
card_holder_name, ..
} = value;
Self { card_holder_name }
}
}
impl From<api_models::payments::BankDebitData> for BankDebitData {
fn from(value: api_models::payments::BankDebitData) -> Self {
match value {
api_models::payments::BankDebitData::AchBankDebit {
account_number,
routing_number,
card_holder_name,
bank_account_holder_name,
bank_name,
bank_type,
bank_holder_type,
..
} => Self::AchBankDebit {
account_number,
routing_number,
card_holder_name,
bank_account_holder_name,
bank_name,
bank_type,
bank_holder_type,
},
api_models::payments::BankDebitData::SepaBankDebit {
iban,
bank_account_holder_name,
..
} => Self::SepaBankDebit {
iban,
bank_account_holder_name,
},
api_models::payments::BankDebitData::BecsBankDebit {
account_number,
bsb_number,
bank_account_holder_name,
..
} => Self::BecsBankDebit {
account_number,
bsb_number,
bank_account_holder_name,
},
api_models::payments::BankDebitData::BacsBankDebit {
account_number,
sort_code,
bank_account_holder_name,
..
} => Self::BacsBankDebit {
account_number,
sort_code,
bank_account_holder_name,
},
}
}
}
impl From<BankDebitData> for api_models::payments::additional_info::BankDebitAdditionalData {
fn from(value: BankDebitData) -> Self {
match value {
BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_name,
bank_type,
bank_holder_type,
card_holder_name,
bank_account_holder_name,
} => Self::Ach(Box::new(
payment_additional_types::AchBankDebitAdditionalData {
account_number: MaskedBankAccount::from(account_number),
routing_number: MaskedRoutingNumber::from(routing_number),
bank_name,
bank_type,
bank_holder_type,
card_holder_name,
bank_account_holder_name,
},
)),
BankDebitData::SepaBankDebit {
iban,
bank_account_holder_name,
} => Self::Sepa(Box::new(
payment_additional_types::SepaBankDebitAdditionalData {
iban: MaskedIban::from(iban),
bank_account_holder_name,
},
)),
BankDebitData::BecsBankDebit {
account_number,
bsb_number,
bank_account_holder_name,
} => Self::Becs(Box::new(
payment_additional_types::BecsBankDebitAdditionalData {
account_number: MaskedBankAccount::from(account_number),
bsb_number,
bank_account_holder_name,
},
)),
BankDebitData::BacsBankDebit {
account_number,
sort_code,
bank_account_holder_name,
} => Self::Bacs(Box::new(
payment_additional_types::BacsBankDebitAdditionalData {
account_number: MaskedBankAccount::from(account_number),
sort_code: MaskedSortCode::from(sort_code),
bank_account_holder_name,
},
)),
}
}
}
impl From<api_models::payments::BankTransferData> for BankTransferData {
fn from(value: api_models::payments::BankTransferData) -> Self {
match value {
api_models::payments::BankTransferData::AchBankTransfer { .. } => {
Self::AchBankTransfer {}
}
api_models::payments::BankTransferData::SepaBankTransfer { .. } => {
Self::SepaBankTransfer {}
}
api_models::payments::BankTransferData::BacsBankTransfer { .. } => {
Self::BacsBankTransfer {}
}
api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
Self::MultibancoBankTransfer {}
}
api_models::payments::BankTransferData::PermataBankTransfer { .. } => {
Self::PermataBankTransfer {}
}
api_models::payments::BankTransferData::BcaBankTransfer { .. } => {
Self::BcaBankTransfer {}
}
api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {
Self::BniVaBankTransfer {}
}
api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {
Self::BriVaBankTransfer {}
}
api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {
Self::CimbVaBankTransfer {}
}
api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
Self::DanamonVaBankTransfer {}
}
api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
Self::MandiriVaBankTransfer {}
}
api_models::payments::BankTransferData::Pix { pix_key, cpf, cnpj } => {
Self::Pix { pix_key, cpf, cnpj }
}
api_models::payments::BankTransferData::Pse {} => Self::Pse {},
api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {
Self::LocalBankTransfer { bank_code }
}
api_models::payments::BankTransferData::InstantBankTransfer {} => {
Self::InstantBankTransfer {}
}
}
}
}
impl From<BankTransferData> for api_models::payments::additional_info::BankTransferAdditionalData {
fn from(value: BankTransferData) -> Self {
match value {
BankTransferData::AchBankTransfer {} => Self::Ach {},
BankTransferData::SepaBankTransfer {} => Self::Sepa {},
BankTransferData::BacsBankTransfer {} => Self::Bacs {},
BankTransferData::MultibancoBankTransfer {} => Self::Multibanco {},
BankTransferData::PermataBankTransfer {} => Self::Permata {},
BankTransferData::BcaBankTransfer {} => Self::Bca {},
BankTransferData::BniVaBankTransfer {} => Self::BniVa {},
BankTransferData::BriVaBankTransfer {} => Self::BriVa {},
BankTransferData::CimbVaBankTransfer {} => Self::CimbVa {},
BankTransferData::DanamonVaBankTransfer {} => Self::DanamonVa {},
BankTransferData::MandiriVaBankTransfer {} => Self::MandiriVa {},
BankTransferData::Pix { pix_key, cpf, cnpj } => Self::Pix(Box::new(
api_models::payments::additional_info::PixBankTransferAdditionalData {
pix_key: pix_key.map(MaskedBankAccount::from),
cpf: cpf.map(MaskedBankAccount::from),
cnpj: cnpj.map(MaskedBankAccount::from),
},
)),
BankTransferData::Pse {} => Self::Pse {},
BankTransferData::LocalBankTransfer { bank_code } => Self::LocalBankTransfer(Box::new(
api_models::payments::additional_info::LocalBankTransferAdditionalData {
bank_code: bank_code.map(MaskedBankAccount::from),
},
)),
BankTransferData::InstantBankTransfer {} => Self::InstantBankTransfer {},
}
}
}
impl From<api_models::payments::RealTimePaymentData> for RealTimePaymentData {
fn from(value: api_models::payments::RealTimePaymentData) -> Self {
match value {
api_models::payments::RealTimePaymentData::Fps {} => Self::Fps {},
api_models::payments::RealTimePaymentData::DuitNow {} => Self::DuitNow {},
api_models::payments::RealTimePaymentData::PromptPay {} => Self::PromptPay {},
api_models::payments::RealTimePaymentData::VietQr {} => Self::VietQr {},
}
}
}
impl From<RealTimePaymentData> for api_models::payments::RealTimePaymentData {
fn from(value: RealTimePaymentData) -> Self {
match value {
RealTimePaymentData::Fps {} => Self::Fps {},
RealTimePaymentData::DuitNow {} => Self::DuitNow {},
RealTimePaymentData::PromptPay {} => Self::PromptPay {},
RealTimePaymentData::VietQr {} => Self::VietQr {},
}
}
}
impl From<api_models::payments::OpenBankingData> for OpenBankingData {
fn from(value: api_models::payments::OpenBankingData) -> Self {
match value {
api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},
}
}
}
impl From<OpenBankingData> for api_models::payments::OpenBankingData {
fn from(value: OpenBankingData) -> Self {
match value {
OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},
}
}
}
impl From<api_models::payments::MobilePaymentData> for MobilePaymentData {
fn from(value: api_models::payments::MobilePaymentData) -> Self {
match value {
api_models::payments::MobilePaymentData::DirectCarrierBilling {
msisdn,
client_uid,
} => Self::DirectCarrierBilling { msisdn, client_uid },
}
}
}
impl From<MobilePaymentData> for api_models::payments::MobilePaymentData {
fn from(value: MobilePaymentData) -> Self {
match value {
MobilePaymentData::DirectCarrierBilling { msisdn, client_uid } => {
Self::DirectCarrierBilling { msisdn, client_uid }
}
}
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue1 {
pub card_number: String,
pub exp_year: String,
pub exp_month: String,
pub nickname: Option<String>,
pub card_last_four: Option<String>,
pub card_token: Option<String>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue2 {
pub card_security_code: Option<String>,
pub card_fingerprint: Option<String>,
pub external_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletValue1 {
pub data: WalletData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankTransferValue1 {
pub data: BankTransferData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankTransferValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectValue1 {
pub data: BankRedirectData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankDebitValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankDebitValue1 {
pub data: BankDebitData,
}
pub trait GetPaymentMethodType {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType;
}
impl GetPaymentMethodType for CardRedirectData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Knet {} => api_enums::PaymentMethodType::Knet,
Self::Benefit {} => api_enums::PaymentMethodType::Benefit,
Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm,
Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect,
}
}
}
impl GetPaymentMethodType for WalletData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay,
Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk,
Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay,
Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,
Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,
Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,
Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash,
Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => {
api_enums::PaymentMethodType::ApplePay
}
Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana,
Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => {
api_enums::PaymentMethodType::GooglePay
}
Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,
Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,
Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,
Self::Paze(_) => api_enums::PaymentMethodType::Paze,
Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay,
Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint,
Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps,
Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo,
Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => {
api_enums::PaymentMethodType::WeChatPay
}
Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp,
Self::SwishQr(_) => api_enums::PaymentMethodType::Swish,
Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity,
}
}
}
impl GetPaymentMethodType for PayLaterData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna,
Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna,
Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm,
Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay,
Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright,
Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley,
Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma,
Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome,
}
}
}
impl GetPaymentMethodType for BankRedirectData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard,
Self::Bizum {} => api_enums::PaymentMethodType::Bizum,
Self::Blik { .. } => api_enums::PaymentMethodType::Blik,
Self::Eft { .. } => api_enums::PaymentMethodType::Eft,
Self::Eps { .. } => api_enums::PaymentMethodType::Eps,
Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay,
Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal,
Self::Interac { .. } => api_enums::PaymentMethodType::Interac,
Self::OnlineBankingCzechRepublic { .. } => {
api_enums::PaymentMethodType::OnlineBankingCzechRepublic
}
Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland,
Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland,
Self::OnlineBankingSlovakia { .. } => {
api_enums::PaymentMethodType::OnlineBankingSlovakia
}
Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk,
Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24,
Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort,
Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly,
Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx,
Self::OnlineBankingThailand { .. } => {
api_enums::PaymentMethodType::OnlineBankingThailand
}
Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect,
}
}
}
impl GetPaymentMethodType for BankDebitData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach,
Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa,
Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs,
Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs,
}
}
}
impl GetPaymentMethodType for BankTransferData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach,
Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::Sepa,
Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs,
Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco,
Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer,
Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer,
Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa,
Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa,
Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa,
Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa,
Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa,
Self::Pix { .. } => api_enums::PaymentMethodType::Pix,
Self::Pse {} => api_enums::PaymentMethodType::Pse,
Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer,
Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer,
}
}
}
impl GetPaymentMethodType for CryptoData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
api_enums::PaymentMethodType::CryptoCurrency
}
}
impl GetPaymentMethodType for RealTimePaymentData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Fps {} => api_enums::PaymentMethodType::Fps,
Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow,
Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay,
Self::VietQr {} => api_enums::PaymentMethodType::VietQr,
}
}
}
impl GetPaymentMethodType for UpiData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect,
Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent,
}
}
}
impl GetPaymentMethodType for VoucherData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Boleto(_) => api_enums::PaymentMethodType::Boleto,
Self::Efecty => api_enums::PaymentMethodType::Efecty,
Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo,
Self::RedCompra => api_enums::PaymentMethodType::RedCompra,
Self::RedPagos => api_enums::PaymentMethodType::RedPagos,
Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart,
Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret,
Self::Oxxo => api_enums::PaymentMethodType::Oxxo,
Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven,
Self::Lawson(_) => api_enums::PaymentMethodType::Lawson,
Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop,
Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart,
Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart,
Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy,
}
}
}
impl GetPaymentMethodType for GiftCardData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Givex(_) => api_enums::PaymentMethodType::Givex,
Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard,
}
}
}
impl GetPaymentMethodType for OpenBankingData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS,
}
}
}
impl GetPaymentMethodType for MobilePaymentData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling,
}
}
}
impl From<Card> for ExtendedCardInfo {
fn from(value: Card) -> Self {
Self {
card_number: value.card_number,
card_exp_month: value.card_exp_month,
card_exp_year: value.card_exp_year,
card_holder_name: None,
card_cvc: value.card_cvc,
card_issuer: value.card_issuer,
card_network: value.card_network,
card_type: value.card_type,
card_issuing_country: value.card_issuing_country,
bank_code: value.bank_code,
}
}
}
impl From<GooglePayWalletData> for payment_methods::PaymentMethodDataWalletInfo {
fn from(item: GooglePayWalletData) -> Self {
Self {
last4: item.info.card_details,
card_network: item.info.card_network,
card_type: Some(item.pm_type),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum PaymentMethodsData {
Card(CardDetailsPaymentMethod),
BankDetails(payment_methods::PaymentMethodDataBankCreds), //PaymentMethodDataBankCreds and its transformations should be moved to the domain models
WalletDetails(payment_methods::PaymentMethodDataWalletInfo), //PaymentMethodDataWalletInfo and its transformations should be moved to the domain models
NetworkToken(NetworkTokenDetailsPaymentMethod),
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct NetworkTokenDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub network_token_expiry_month: Option<Secret<String>>,
pub network_token_expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
}
fn saved_in_locker_default() -> bool {
true
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CardDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {
fn from(item: payment_methods::CardDetail) -> Self {
Self {
issuer_country: item.card_issuing_country.map(|c| c.to_string()),
last4_digits: Some(item.card_number.get_last4()),
expiry_month: Some(item.card_exp_month),
expiry_year: Some(item.card_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
}
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod {
fn from(item: NetworkTokenDetails) -> Self {
Self {
issuer_country: item.card_issuing_country.map(|c| c.to_string()),
last4_digits: Some(item.network_token.get_last4()),
network_token_expiry_month: Some(item.network_token_exp_month),
network_token_expiry_year: Some(item.network_token_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
}
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct SingleUsePaymentMethodToken {
pub token: Secret<String>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl SingleUsePaymentMethodToken {
pub fn get_single_use_token_from_payment_method_token(
token: Secret<String>,
mca_id: id_type::MerchantConnectorAccountId,
) -> Self {
Self {
token,
merchant_connector_id: mca_id,
}
}
}
impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod {
fn from(item: NetworkTokenDetailsPaymentMethod) -> Self {
Self {
last4_digits: item.last4_digits,
issuer_country: item.issuer_country,
network_token_expiry_month: item.network_token_expiry_month,
network_token_expiry_year: item.network_token_expiry_year,
nick_name: item.nick_name,
card_holder_name: item.card_holder_name,
card_isin: item.card_isin,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type,
saved_to_locker: item.saved_to_locker,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SingleUseTokenKey(String);
#[cfg(feature = "v2")]
impl SingleUseTokenKey {
pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self {
let new_token = format!("single_use_token_{}", payment_method_id.get_string_repr());
Self(new_token)
}
pub fn get_store_key(&self) -> &str {
&self.0
}
}
| 17,798 | 2,389 |
hyperswitch | crates/hyperswitch_domain_models/src/payments.rs | .rs | #[cfg(feature = "v2")]
use std::marker::PhantomData;
#[cfg(feature = "v2")]
use api_models::payments::SessionToken;
use common_types::primitive_wrappers::{
AlwaysRequestExtendedAuthorization, RequestExtendedAuthorizationBool,
};
#[cfg(feature = "v2")]
use common_utils::ext_traits::OptionExt;
use common_utils::{
self,
crypto::Encryptable,
encryption::Encryption,
errors::CustomResult,
ext_traits::ValueExt,
id_type, pii,
types::{keymanager::ToEncryptable, MinorUnit},
};
use diesel_models::payment_intent::TaxDetails;
#[cfg(feature = "v2")]
use error_stack::ResultExt;
use masking::Secret;
#[cfg(feature = "v2")]
use payment_intent::PaymentIntentUpdate;
use router_derive::ToEncryption;
use rustc_hash::FxHashMap;
use serde_json::Value;
use time::PrimitiveDateTime;
pub mod payment_attempt;
pub mod payment_intent;
use common_enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::{
ephemeral_key,
types::{FeatureMetadata, OrderDetailsWithAmount},
};
use self::payment_attempt::PaymentAttempt;
#[cfg(feature = "v2")]
use crate::{
address::Address, business_profile, customer, errors, merchant_account,
merchant_connector_account, payment_address, payment_method_data, routing,
ApiModelToDieselModelConvertor,
};
#[cfg(feature = "v1")]
use crate::{payment_method_data, RemoteStorageObject};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub shipping_cost: Option<MinorUnit>,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<Value>,
pub connector_id: Option<String>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt: RemoteStorageObject<PaymentAttempt>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<Value>,
pub connector_metadata: Option<Value>,
pub feature_metadata: Option<Value>,
pub attempt_count: i16,
pub profile_id: Option<id_type::ProfileId>,
pub payment_link_id: Option<String>,
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub merchant_decision: Option<String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
pub fingerprint_id: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
#[encrypt]
pub customer_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub merchant_order_reference_id: Option<String>,
#[encrypt]
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub platform_merchant_id: Option<id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
}
impl PaymentIntent {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::PaymentId {
&self.payment_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentId {
&self.id
}
#[cfg(feature = "v2")]
/// This is the url to which the customer will be redirected to, to complete the redirection flow
pub fn create_start_redirection_url(
&self,
base_url: &str,
publishable_key: String,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let start_redirection_url = &format!(
"{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}",
base_url,
self.get_id().get_string_repr(),
publishable_key,
self.profile_id.get_string_repr()
);
url::Url::parse(start_redirection_url)
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error creating start redirection url")
}
#[cfg(feature = "v1")]
pub fn get_request_extended_authorization_bool_if_connector_supports(
&self,
connector: common_enums::connector_enums::Connector,
always_request_extended_authorization_optional: Option<AlwaysRequestExtendedAuthorization>,
payment_method_optional: Option<common_enums::PaymentMethod>,
payment_method_type_optional: Option<common_enums::PaymentMethodType>,
) -> Option<RequestExtendedAuthorizationBool> {
use router_env::logger;
let is_extended_authorization_supported_by_connector = || {
let supported_pms = connector.get_payment_methods_supporting_extended_authorization();
let supported_pmts =
connector.get_payment_method_types_supporting_extended_authorization();
// check if payment method or payment method type is supported by the connector
logger::info!(
"Extended Authentication Connector:{:?}, Supported payment methods: {:?}, Supported payment method types: {:?}, Payment method Selected: {:?}, Payment method type Selected: {:?}",
connector,
supported_pms,
supported_pmts,
payment_method_optional,
payment_method_type_optional
);
match (payment_method_optional, payment_method_type_optional) {
(Some(payment_method), Some(payment_method_type)) => {
supported_pms.contains(&payment_method)
&& supported_pmts.contains(&payment_method_type)
}
(Some(payment_method), None) => supported_pms.contains(&payment_method),
(None, Some(payment_method_type)) => supported_pmts.contains(&payment_method_type),
(None, None) => false,
}
};
let intent_request_extended_authorization_optional = self.request_extended_authorization;
if always_request_extended_authorization_optional.is_some_and(
|always_request_extended_authorization| *always_request_extended_authorization,
) || intent_request_extended_authorization_optional.is_some_and(
|intent_request_extended_authorization| *intent_request_extended_authorization,
) {
Some(is_extended_authorization_supported_by_connector())
} else {
None
}
.map(RequestExtendedAuthorizationBool::from)
}
#[cfg(feature = "v2")]
/// This is the url to which the customer will be redirected to, after completing the redirection flow
pub fn create_finish_redirection_url(
&self,
base_url: &str,
publishable_key: &str,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let finish_redirection_url = format!(
"{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}",
self.id.get_string_repr(),
self.profile_id.get_string_repr()
);
url::Url::parse(&finish_redirection_url)
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error creating finish redirection url")
}
pub fn parse_and_get_metadata<T>(
&self,
type_name: &'static str,
) -> CustomResult<Option<T>, common_utils::errors::ParsingError>
where
T: for<'de> masking::Deserialize<'de>,
{
self.metadata
.clone()
.map(|metadata| metadata.parse_value(type_name))
.transpose()
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct AmountDetails {
/// The amount of the order in the lowest denomination of currency
pub order_amount: MinorUnit,
/// The currency of the order
pub currency: common_enums::Currency,
/// The shipping cost of the order. This has to be collected from the merchant
pub shipping_cost: Option<MinorUnit>,
/// Tax details related to the order. This will be calculated by the external tax provider
pub tax_details: Option<TaxDetails>,
/// The action to whether calculate tax by calling external tax provider or not
pub skip_external_tax_calculation: common_enums::TaxCalculationOverride,
/// The action to whether calculate surcharge or not
pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride,
/// The surcharge amount to be added to the order, collected from the merchant
pub surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
pub tax_on_surcharge: Option<MinorUnit>,
/// The total amount captured for the order. This is the sum of all the captured amounts for the order.
/// For automatic captures, this will be the same as net amount for the order
pub amount_captured: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
impl AmountDetails {
/// Get the action to whether calculate surcharge or not as a boolean value
fn get_surcharge_action_as_bool(&self) -> bool {
self.skip_surcharge_calculation.as_bool()
}
/// Get the action to whether calculate external tax or not as a boolean value
fn get_external_tax_action_as_bool(&self) -> bool {
self.skip_external_tax_calculation.as_bool()
}
/// Calculate the net amount for the order
pub fn calculate_net_amount(&self) -> MinorUnit {
self.order_amount
+ self.shipping_cost.unwrap_or(MinorUnit::zero())
+ self.surcharge_amount.unwrap_or(MinorUnit::zero())
+ self.tax_on_surcharge.unwrap_or(MinorUnit::zero())
}
pub fn create_attempt_amount_details(
&self,
confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => {
self.tax_details.as_ref().and_then(|tax_details| {
tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype))
})
}
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
})
}
pub fn proxy_create_attempt_amount_details(
&self,
_confirm_intent_request: &api_models::payments::ProxyPaymentsRequest,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => self
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.get_tax_amount(None)),
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
})
}
pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self {
Self {
order_amount: req
.order_amount()
.unwrap_or(self.order_amount.into())
.into(),
currency: req.currency().unwrap_or(self.currency),
shipping_cost: req.shipping_cost().or(self.shipping_cost),
tax_details: req
.order_tax_amount()
.map(|order_tax_amount| TaxDetails {
default: Some(diesel_models::DefaultTax { order_tax_amount }),
payment_method_type: None,
})
.or(self.tax_details),
skip_external_tax_calculation: req
.skip_external_tax_calculation()
.unwrap_or(self.skip_external_tax_calculation),
skip_surcharge_calculation: req
.skip_surcharge_calculation()
.unwrap_or(self.skip_surcharge_calculation),
surcharge_amount: req.surcharge_amount().or(self.surcharge_amount),
tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge),
amount_captured: self.amount_captured,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
/// The global identifier for the payment intent. This is generated by the system.
/// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`.
pub id: id_type::GlobalPaymentId,
/// The identifier for the merchant. This is automatically derived from the api key used to create the payment.
pub merchant_id: id_type::MerchantId,
/// The status of payment intent.
pub status: storage_enums::IntentStatus,
/// The amount related details of the payment
pub amount_details: AmountDetails,
/// The total amount captured for the order. This is the sum of all the captured amounts for the order.
pub amount_captured: Option<MinorUnit>,
/// The identifier for the customer. This is the identifier for the customer in the merchant's system.
pub customer_id: Option<id_type::GlobalCustomerId>,
/// The description of the order. This will be passed to connectors which support description.
pub description: Option<common_utils::types::Description>,
/// The return url for the payment. This is the url to which the user will be redirected after the payment is completed.
pub return_url: Option<common_utils::types::Url>,
/// The metadata for the payment intent. This is the metadata that will be passed to the connectors.
pub metadata: Option<pii::SecretSerdeValue>,
/// The statement descriptor for the order, this will be displayed in the user's bank statement.
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
/// The time at which the order was created
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The time at which the order was last modified
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
/// The client secret that is generated for the payment. This is used to authenticate the payment from client facing apis.
pub client_secret: common_utils::types::ClientSecret,
/// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent.
pub active_attempt_id: Option<id_type::GlobalAttemptId>,
/// The order details for the payment.
pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>,
/// This is the list of payment method types that are allowed for the payment intent.
/// This field allows the merchant to restrict the payment methods that can be used for the payment intent.
pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,
/// This metadata contains details about
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub feature_metadata: Option<FeatureMetadata>,
/// Number of attempts that have been made for the order
pub attempt_count: i16,
/// The profile id for the payment.
pub profile_id: id_type::ProfileId,
/// The payment link id for the payment. This is generated only if `enable_payment_link` is set to true.
pub payment_link_id: Option<String>,
/// This Denotes the action(approve or reject) taken by merchant in case of manual review.
/// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
/// Denotes the last instance which updated the payment
pub updated_by: String,
/// Denotes whether merchant requested for incremental authorization to be enabled for this payment.
pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization,
/// Denotes the number of authorizations that have been made for the payment.
pub authorization_count: Option<i32>,
/// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire.
#[serde(with = "common_utils::custom_serde::iso8601")]
pub session_expiry: PrimitiveDateTime,
/// Denotes whether merchant requested for 3ds authentication to be enabled for this payment.
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
/// Metadata related to fraud and risk management
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// The details of the customer in a denormalized form. Only a subset of fields are stored.
#[encrypt]
pub customer_details: Option<Encryptable<Secret<Value>>>,
/// The reference id for the order in the merchant's system. This value can be passed by the merchant.
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The billing address for the order in a denormalized form.
#[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<Address>>,
/// The shipping address for the order in a denormalized form.
#[encrypt(ty = Value)]
pub shipping_address: Option<Encryptable<Address>>,
/// Capture method for the payment
pub capture_method: storage_enums::CaptureMethod,
/// Authentication type that is requested by the merchant for this payment.
pub authentication_type: Option<common_enums::AuthenticationType>,
/// This contains the pre routing results that are done when routing is done during listing the payment methods.
pub prerouting_algorithm: Option<routing::PaymentRoutingInfo>,
/// The organization id for the payment. This is derived from the merchant account
pub organization_id: id_type::OrganizationId,
/// Denotes the request by the merchant whether to enable a payment link for this payment.
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
/// Denotes the request by the merchant whether to apply MIT exemption for this payment
pub apply_mit_exemption: common_enums::MitExemptionRequest,
/// Denotes whether the customer is present during the payment flow. This information may be used for 3ds authentication
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
/// Denotes the override for payment link configuration
pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>,
/// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile.
pub routing_algorithm_id: Option<id_type::RoutingId>,
/// Identifier for the platform merchant.
pub platform_merchant_id: Option<id_type::MerchantId>,
/// Split Payment Data
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
}
#[cfg(feature = "v2")]
impl PaymentIntent {
fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_payment_method_sub_type())
}
fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_payment_method_type())
}
pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())
.map(|recovery_metadata| {
recovery_metadata
.billing_connector_payment_details
.connector_customer_id
.clone()
})
}
pub fn get_billing_merchant_connector_account_id(
&self,
) -> Option<id_type::MerchantConnectorAccountId> {
self.feature_metadata.as_ref().and_then(|feature_metadata| {
feature_metadata.get_billing_merchant_connector_account_id()
})
}
fn get_request_incremental_authorization_value(
request: &api_models::payments::PaymentsCreateIntentRequest,
) -> CustomResult<
common_enums::RequestIncrementalAuthorization,
errors::api_error_response::ApiErrorResponse,
> {
request.request_incremental_authorization
.map(|request_incremental_authorization| {
if request_incremental_authorization == common_enums::RequestIncrementalAuthorization::True {
if request.capture_method == Some(common_enums::CaptureMethod::Automatic) {
Err(errors::api_error_response::ApiErrorResponse::InvalidRequestData { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })?
}
Ok(common_enums::RequestIncrementalAuthorization::True)
} else {
Ok(common_enums::RequestIncrementalAuthorization::False)
}
})
.unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default()))
}
/// Check if the client secret is associated with the payment and if it has been expired
pub fn validate_client_secret(
&self,
client_secret: &common_utils::types::ClientSecret,
) -> Result<(), errors::api_error_response::ApiErrorResponse> {
common_utils::fp_utils::when(self.client_secret != *client_secret, || {
Err(errors::api_error_response::ApiErrorResponse::ClientSecretInvalid)
})?;
common_utils::fp_utils::when(self.session_expiry < common_utils::date_time::now(), || {
Err(errors::api_error_response::ApiErrorResponse::ClientSecretExpired)
})?;
Ok(())
}
pub async fn create_domain_model_from_request(
payment_id: &id_type::GlobalPaymentId,
merchant_account: &merchant_account::MerchantAccount,
profile: &business_profile::Profile,
request: api_models::payments::PaymentsCreateIntentRequest,
decrypted_payment_intent: DecryptedPaymentIntent,
platform_merchant_id: Option<&merchant_account::MerchantAccount>,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting connector metadata as value")?;
let request_incremental_authorization =
Self::get_request_incremental_authorization_value(&request)?;
let allowed_payment_method_types = request.allowed_payment_method_types;
let session_expiry =
common_utils::date_time::now().saturating_add(time::Duration::seconds(
request.session_expiry.map(i64::from).unwrap_or(
profile
.session_expiry
.unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY),
),
));
let client_secret = payment_id.generate_client_secret();
let order_details = request.order_details.map(|order_details| {
order_details
.into_iter()
.map(|order_detail| Secret::new(OrderDetailsWithAmount::convert_from(order_detail)))
.collect()
});
Ok(Self {
id: payment_id.clone(),
merchant_id: merchant_account.get_id().clone(),
// Intent status would be RequiresPaymentMethod because we are creating a new payment intent
status: common_enums::IntentStatus::RequiresPaymentMethod,
amount_details: AmountDetails::from(request.amount_details),
amount_captured: None,
customer_id: request.customer_id,
description: request.description,
return_url: request.return_url,
metadata: request.metadata,
statement_descriptor: request.statement_descriptor,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: request.setup_future_usage.unwrap_or_default(),
client_secret,
active_attempt_id: None,
order_details,
allowed_payment_method_types,
connector_metadata,
feature_metadata: request.feature_metadata.map(FeatureMetadata::convert_from),
// Attempt count is 0 in create intent as no attempt is made yet
attempt_count: 0,
profile_id: profile.get_id().clone(),
payment_link_id: None,
frm_merchant_decision: None,
updated_by: merchant_account.storage_scheme.to_string(),
request_incremental_authorization,
// Authorization count is 0 in create intent as no authorization is made yet
authorization_count: Some(0),
session_expiry,
request_external_three_ds_authentication: request
.request_external_three_ds_authentication
.unwrap_or_default(),
frm_metadata: request.frm_metadata,
customer_details: None,
merchant_reference_id: request.merchant_reference_id,
billing_address: decrypted_payment_intent
.billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?,
shipping_address: decrypted_payment_intent
.shipping_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode shipping address")?,
capture_method: request.capture_method.unwrap_or_default(),
authentication_type: request.authentication_type,
prerouting_algorithm: None,
organization_id: merchant_account.organization_id.clone(),
enable_payment_link: request.payment_link_enabled.unwrap_or_default(),
apply_mit_exemption: request.apply_mit_exemption.unwrap_or_default(),
customer_present: request.customer_present.unwrap_or_default(),
payment_link_config: request
.payment_link_config
.map(ApiModelToDieselModelConvertor::convert_from),
routing_algorithm_id: request.routing_algorithm_id,
platform_merchant_id: platform_merchant_id
.map(|merchant_account| merchant_account.get_id().to_owned()),
split_payments: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
})
}
pub fn get_revenue_recovery_metadata(
&self,
) -> Option<diesel_models::types::PaymentRevenueRecoveryMetadata> {
self.feature_metadata
.as_ref()
.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
}
pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> {
self.feature_metadata.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Default, Debug, Clone)]
pub struct HeaderPayload {
pub payment_confirm_source: Option<common_enums::PaymentSource>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub x_hs_latency: Option<bool>,
pub browser_name: Option<common_enums::BrowserName>,
pub x_client_platform: Option<common_enums::ClientPlatform>,
pub x_merchant_domain: Option<String>,
pub locale: Option<String>,
pub x_app_id: Option<String>,
pub x_redirect_uri: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ClickToPayMetaData {
pub dpa_id: String,
pub dpa_name: String,
pub locale: String,
pub card_brands: Vec<String>,
pub acquirer_bin: String,
pub acquirer_merchant_id: String,
pub merchant_category_code: String,
pub merchant_country_code: String,
pub dpa_client_id: Option<String>,
}
// TODO: uncomment fields as necessary
#[cfg(feature = "v2")]
#[derive(Default, Debug, Clone)]
pub struct HeaderPayload {
/// The source with which the payment is confirmed.
pub payment_confirm_source: Option<common_enums::PaymentSource>,
// pub client_source: Option<String>,
// pub client_version: Option<String>,
pub x_hs_latency: Option<bool>,
pub browser_name: Option<common_enums::BrowserName>,
pub x_client_platform: Option<common_enums::ClientPlatform>,
pub x_merchant_domain: Option<String>,
pub locale: Option<String>,
pub x_app_id: Option<String>,
pub x_redirect_uri: Option<String>,
pub client_secret: Option<common_utils::types::ClientSecret>,
}
impl HeaderPayload {
pub fn with_source(payment_confirm_source: common_enums::PaymentSource) -> Self {
Self {
payment_confirm_source: Some(payment_confirm_source),
..Default::default()
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentIntentData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub sessions_token: Vec<SessionToken>,
}
// TODO: Check if this can be merged with existing payment data
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct PaymentConfirmData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub payment_method_data: Option<payment_method_data::PaymentMethodData>,
pub payment_address: payment_address::PaymentAddress,
pub mandate_data: Option<api_models::payments::MandateIds>,
}
#[cfg(feature = "v2")]
impl<F: Clone> PaymentConfirmData<F> {
pub fn get_connector_customer_id(
&self,
customer: Option<&customer::Customer>,
merchant_connector_account: &merchant_connector_account::MerchantConnectorAccount,
) -> Option<String> {
match customer
.and_then(|cust| cust.get_connector_customer_id(&merchant_connector_account.get_id()))
{
Some(id) => Some(id.to_string()),
None => self
.payment_intent
.get_connector_customer_id_from_feature_metadata(),
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentStatusData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: Option<PaymentAttempt>,
pub payment_address: payment_address::PaymentAddress,
pub attempts: Option<Vec<PaymentAttempt>>,
/// Should the payment status be synced with connector
/// This will depend on the payment status and the force sync flag in the request
pub should_sync_with_connector: bool,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentCaptureData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
}
#[cfg(feature = "v2")]
impl<F> PaymentStatusData<F>
where
F: Clone,
{
pub fn get_payment_id(&self) -> &id_type::GlobalPaymentId {
&self.payment_intent.id
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentAttemptRecordData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub revenue_recovery_data: RevenueRecoveryData,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct RevenueRecoveryData {
pub billing_connector_id: id_type::MerchantConnectorAccountId,
pub processor_payment_method_token: String,
pub connector_customer_id: String,
}
#[cfg(feature = "v2")]
impl<F> PaymentAttemptRecordData<F>
where
F: Clone,
{
pub fn get_updated_feature_metadata(
&self,
) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> {
let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata();
let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata();
let payment_attempt_connector = self.payment_attempt.connector.clone();
let payment_revenue_recovery_metadata = match payment_attempt_connector {
Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata {
// Update retry count by one.
total_retry_count: revenue_recovery
.as_ref()
.map_or(1, |data| (data.total_retry_count + 1)),
// Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded.
payment_connector_transmission:
common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(),
active_attempt_payment_connector_id: self
.payment_attempt
.get_attempt_merchant_connector_account_id()?,
billing_connector_payment_details:
diesel_models::types::BillingConnectorPaymentDetails {
payment_processor_token: self
.revenue_recovery_data
.processor_payment_method_token
.clone(),
connector_customer_id: self
.revenue_recovery_data
.connector_customer_id
.clone(),
},
payment_method_type: self.payment_attempt.payment_method_type,
payment_method_subtype: self.payment_attempt.payment_method_subtype,
connector: connector.parse().map_err(|err| {
router_env::logger::error!(?err, "Failed to parse connector string to enum");
errors::api_error_response::ApiErrorResponse::InternalServerError
})?,
}),
None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found in payment attempt")?,
};
Ok(Some(FeatureMetadata {
redirect_response: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.redirect_response.clone()),
search_tags: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.search_tags.clone()),
apple_pay_recurring_details: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.apple_pay_recurring_details.clone()),
payment_revenue_recovery_metadata,
}))
}
}
#[derive(Clone, serde::Serialize, Debug)]
pub enum VaultOperation {
ExistingVaultData(VaultData),
}
impl VaultOperation {
pub fn get_updated_vault_data(
existing_vault_data: Option<&Self>,
payment_method_data: &payment_method_data::PaymentMethodData,
) -> Option<Self> {
match (existing_vault_data, payment_method_data) {
(None, payment_method_data::PaymentMethodData::Card(card)) => {
Some(Self::ExistingVaultData(VaultData::Card(card.clone())))
}
(None, payment_method_data::PaymentMethodData::NetworkToken(nt_data)) => Some(
Self::ExistingVaultData(VaultData::NetworkToken(nt_data.clone())),
),
(Some(Self::ExistingVaultData(vault_data)), payment_method_data) => {
match (vault_data, payment_method_data) {
(
VaultData::Card(card),
payment_method_data::PaymentMethodData::NetworkToken(nt_data),
) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken(
Box::new(CardAndNetworkTokenData {
card_data: card.clone(),
network_token_data: nt_data.clone(),
}),
))),
(
VaultData::NetworkToken(nt_data),
payment_method_data::PaymentMethodData::Card(card),
) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken(
Box::new(CardAndNetworkTokenData {
card_data: card.clone(),
network_token_data: nt_data.clone(),
}),
))),
_ => Some(Self::ExistingVaultData(vault_data.clone())),
}
}
//payment_method_data is not card or network token
_ => None,
}
}
}
#[derive(Clone, serde::Serialize, Debug)]
pub enum VaultData {
Card(payment_method_data::Card),
NetworkToken(payment_method_data::NetworkTokenData),
CardAndNetworkToken(Box<CardAndNetworkTokenData>),
}
#[derive(Default, Clone, serde::Serialize, Debug)]
pub struct CardAndNetworkTokenData {
pub card_data: payment_method_data::Card,
pub network_token_data: payment_method_data::NetworkTokenData,
}
impl VaultData {
pub fn get_card_vault_data(&self) -> Option<payment_method_data::Card> {
match self {
Self::Card(card_data) => Some(card_data.clone()),
Self::NetworkToken(_network_token_data) => None,
Self::CardAndNetworkToken(vault_data) => Some(vault_data.card_data.clone()),
}
}
pub fn get_network_token_data(&self) -> Option<payment_method_data::NetworkTokenData> {
match self {
Self::Card(_card_data) => None,
Self::NetworkToken(network_token_data) => Some(network_token_data.clone()),
Self::CardAndNetworkToken(vault_data) => Some(vault_data.network_token_data.clone()),
}
}
}
| 8,694 | 2,390 |
hyperswitch | crates/hyperswitch_domain_models/src/address.rs | .rs | use masking::{PeekInterface, Secret};
#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Address {
pub address: Option<AddressDetails>,
pub phone: Option<PhoneDetails>,
pub email: Option<common_utils::pii::Email>,
}
impl masking::SerializableSecret for Address {}
impl Address {
/// Unify the address, giving priority to `self` when details are present in both
pub fn unify_address(&self, other: Option<&Self>) -> Self {
let other_address_details = other.and_then(|address| address.address.as_ref());
Self {
address: self
.address
.as_ref()
.map(|address| address.unify_address_details(other_address_details))
.or(other_address_details.cloned()),
email: self
.email
.clone()
.or(other.and_then(|other| other.email.clone())),
phone: {
self.phone
.clone()
.and_then(|phone_details| {
if phone_details.number.is_some() {
Some(phone_details)
} else {
None
}
})
.or_else(|| other.and_then(|other| other.phone.clone()))
},
}
}
}
#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)]
pub struct AddressDetails {
pub city: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
}
impl AddressDetails {
pub fn get_optional_full_name(&self) -> Option<Secret<String>> {
match (self.first_name.as_ref(), self.last_name.as_ref()) {
(Some(first_name), Some(last_name)) => Some(Secret::new(format!(
"{} {}",
first_name.peek(),
last_name.peek()
))),
(Some(name), None) | (None, Some(name)) => Some(name.to_owned()),
_ => None,
}
}
/// Unify the address details, giving priority to `self` when details are present in both
pub fn unify_address_details(&self, other: Option<&Self>) -> Self {
if let Some(other) = other {
let (first_name, last_name) = if self
.first_name
.as_ref()
.is_some_and(|first_name| !first_name.peek().trim().is_empty())
{
(self.first_name.clone(), self.last_name.clone())
} else {
(other.first_name.clone(), other.last_name.clone())
};
Self {
first_name,
last_name,
city: self.city.clone().or(other.city.clone()),
country: self.country.or(other.country),
line1: self.line1.clone().or(other.line1.clone()),
line2: self.line2.clone().or(other.line2.clone()),
line3: self.line3.clone().or(other.line3.clone()),
zip: self.zip.clone().or(other.zip.clone()),
state: self.state.clone().or(other.state.clone()),
}
} else {
self.clone()
}
}
}
#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct PhoneDetails {
pub number: Option<Secret<String>>,
pub country_code: Option<String>,
}
impl From<api_models::payments::Address> for Address {
fn from(address: api_models::payments::Address) -> Self {
Self {
address: address.address.map(AddressDetails::from),
phone: address.phone.map(PhoneDetails::from),
email: address.email,
}
}
}
impl From<api_models::payments::AddressDetails> for AddressDetails {
fn from(address: api_models::payments::AddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
line3: address.line3,
zip: address.zip,
state: address.state,
first_name: address.first_name,
last_name: address.last_name,
}
}
}
impl From<api_models::payments::PhoneDetails> for PhoneDetails {
fn from(phone: api_models::payments::PhoneDetails) -> Self {
Self {
number: phone.number,
country_code: phone.country_code,
}
}
}
impl From<Address> for api_models::payments::Address {
fn from(address: Address) -> Self {
Self {
address: address
.address
.map(api_models::payments::AddressDetails::from),
phone: address.phone.map(api_models::payments::PhoneDetails::from),
email: address.email,
}
}
}
impl From<AddressDetails> for api_models::payments::AddressDetails {
fn from(address: AddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
line3: address.line3,
zip: address.zip,
state: address.state,
first_name: address.first_name,
last_name: address.last_name,
}
}
}
impl From<PhoneDetails> for api_models::payments::PhoneDetails {
fn from(phone: PhoneDetails) -> Self {
Self {
number: phone.number,
country_code: phone.country_code,
}
}
}
| 1,201 | 2,391 |
hyperswitch | crates/hyperswitch_domain_models/src/callback_mapper.rs | .rs | use common_utils::pii;
use serde::{self, Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CallbackMapper {
pub id: String,
#[serde(rename = "type")]
pub type_: String,
pub data: pii::SecretSerdeValue,
pub created_at: time::PrimitiveDateTime,
pub last_modified_at: time::PrimitiveDateTime,
}
| 87 | 2,392 |
hyperswitch | crates/hyperswitch_domain_models/src/mandates.rs | .rs | use std::collections::HashMap;
use api_models::payments::{
AcceptanceType as ApiAcceptanceType, CustomerAcceptance as ApiCustomerAcceptance,
MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType,
OnlineMandate as ApiOnlineMandate,
};
use common_enums::Currency;
use common_utils::{
date_time,
errors::{CustomResult, ParsingError},
pii,
types::MinorUnit,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
}
impl From<MandateDetails> for diesel_models::enums::MandateDetails {
fn from(value: MandateDetails) -> Self {
Self {
update_mandate_id: value.update_mandate_id,
}
}
}
impl From<diesel_models::enums::MandateDetails> for MandateDetails {
fn from(value: diesel_models::enums::MandateDetails) -> Self {
Self {
update_mandate_id: value.update_mandate_id,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
}
// The fields on this struct are optional, as we want to allow the merchant to provide partial
// information about creating mandates
#[derive(Default, Eq, PartialEq, Debug, Clone)]
pub struct MandateData {
/// A way to update the mandate's payment method details
pub update_mandate_id: Option<String>,
/// A consent from the customer to store the payment method
pub customer_acceptance: Option<CustomerAcceptance>,
/// A way to select the type of mandate used
pub mandate_type: Option<MandateDataType>,
}
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
pub acceptance_type: AcceptanceType,
/// Specifying when the customer acceptance was provided
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
pub online: Option<OnlineMandate>,
}
#[derive(Default, Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AcceptanceType {
Online,
#[default]
Offline,
}
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[serde(skip_deserializing)]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
/// The user-agent of the customer's browser
pub user_agent: String,
}
impl From<MandateType> for MandateDataType {
fn from(mandate_type: MandateType) -> Self {
match mandate_type {
MandateType::SingleUse(mandate_amount_data) => {
Self::SingleUse(mandate_amount_data.into())
}
MandateType::MultiUse(mandate_amount_data) => {
Self::MultiUse(mandate_amount_data.map(|d| d.into()))
}
}
}
}
impl From<MandateDataType> for diesel_models::enums::MandateDataType {
fn from(value: MandateDataType) -> Self {
match value {
MandateDataType::SingleUse(data) => Self::SingleUse(data.into()),
MandateDataType::MultiUse(None) => Self::MultiUse(None),
MandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())),
}
}
}
impl From<diesel_models::enums::MandateDataType> for MandateDataType {
fn from(value: diesel_models::enums::MandateDataType) -> Self {
use diesel_models::enums::MandateDataType as DieselMandateDataType;
match value {
DieselMandateDataType::SingleUse(data) => Self::SingleUse(data.into()),
DieselMandateDataType::MultiUse(None) => Self::MultiUse(None),
DieselMandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())),
}
}
}
impl From<ApiMandateAmountData> for MandateAmountData {
fn from(value: ApiMandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<MandateAmountData> for diesel_models::enums::MandateAmountData {
fn from(value: MandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<diesel_models::enums::MandateAmountData> for MandateAmountData {
fn from(value: diesel_models::enums::MandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<ApiMandateData> for MandateData {
fn from(value: ApiMandateData) -> Self {
Self {
customer_acceptance: value.customer_acceptance.map(|d| d.into()),
mandate_type: value.mandate_type.map(|d| d.into()),
update_mandate_id: value.update_mandate_id,
}
}
}
impl From<ApiCustomerAcceptance> for CustomerAcceptance {
fn from(value: ApiCustomerAcceptance) -> Self {
Self {
acceptance_type: value.acceptance_type.into(),
accepted_at: value.accepted_at,
online: value.online.map(|d| d.into()),
}
}
}
impl From<CustomerAcceptance> for ApiCustomerAcceptance {
fn from(value: CustomerAcceptance) -> Self {
Self {
acceptance_type: value.acceptance_type.into(),
accepted_at: value.accepted_at,
online: value.online.map(|d| d.into()),
}
}
}
impl From<ApiAcceptanceType> for AcceptanceType {
fn from(value: ApiAcceptanceType) -> Self {
match value {
ApiAcceptanceType::Online => Self::Online,
ApiAcceptanceType::Offline => Self::Offline,
}
}
}
impl From<AcceptanceType> for ApiAcceptanceType {
fn from(value: AcceptanceType) -> Self {
match value {
AcceptanceType::Online => Self::Online,
AcceptanceType::Offline => Self::Offline,
}
}
}
impl From<ApiOnlineMandate> for OnlineMandate {
fn from(value: ApiOnlineMandate) -> Self {
Self {
ip_address: value.ip_address,
user_agent: value.user_agent,
}
}
}
impl From<OnlineMandate> for ApiOnlineMandate {
fn from(value: OnlineMandate) -> Self {
Self {
ip_address: value.ip_address,
user_agent: value.user_agent,
}
}
}
impl CustomerAcceptance {
pub fn get_ip_address(&self) -> Option<String> {
self.online
.as_ref()
.and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned()))
}
pub fn get_user_agent(&self) -> Option<String> {
self.online.as_ref().map(|data| data.user_agent.clone())
}
pub fn get_accepted_at(&self) -> PrimitiveDateTime {
self.accepted_at.unwrap_or_else(date_time::now)
}
}
impl MandateAmountData {
pub fn get_end_date(
&self,
format: date_time::DateFormat,
) -> error_stack::Result<Option<String>, ParsingError> {
self.end_date
.map(|date| {
date_time::format_date(date, format)
.change_context(ParsingError::DateTimeParsingError)
})
.transpose()
}
pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone()
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReferenceRecord {
pub connector_mandate_id: String,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<Currency>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
pub connector_mandate_request_reference_id: Option<String>,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorTokenReferenceRecord {
pub connector_token: String,
pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<MinorUnit>,
pub original_payment_authorized_currency: Option<Currency>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_token_status: common_enums::ConnectorTokenStatus,
pub connector_token_request_reference_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
impl std::ops::Deref for PayoutsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PayoutsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
);
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::Deref for PaymentsTokenReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for PaymentsTokenReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsTokenReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl CommonMandateReference {
pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> {
let mut payments = self
.payments
.as_ref()
.map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value)
.change_context(ParsingError::StructParseFailure("payment mandate details"))?;
self.payouts
.as_ref()
.map(|payouts_mandate| {
serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| {
payments.as_object_mut().map(|payments_object| {
payments_object.insert("payouts".to_string(), payouts_mandate_value);
})
})
})
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
Ok(payments)
}
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
&mut self,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
record: ConnectorTokenReferenceRecord,
) {
match self.payments {
Some(ref mut payments_reference) => {
payments_reference.insert(connector_id.clone(), record);
}
None => {
let mut payments_reference = HashMap::new();
payments_reference.insert(connector_id.clone(), record);
self.payments = Some(PaymentsTokenReference(payments_reference));
}
}
}
}
impl From<diesel_models::CommonMandateReference> for CommonMandateReference {
fn from(value: diesel_models::CommonMandateReference) -> Self {
Self {
payments: value.payments.map(|payments| payments.into()),
payouts: value.payouts.map(|payouts| payouts.into()),
}
}
}
impl From<CommonMandateReference> for diesel_models::CommonMandateReference {
fn from(value: CommonMandateReference) -> Self {
Self {
payments: value.payments.map(|payments| payments.into()),
payouts: value.payouts.map(|payouts| payouts.into()),
}
}
}
impl From<diesel_models::PayoutsMandateReference> for PayoutsMandateReference {
fn from(value: diesel_models::PayoutsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
impl From<PayoutsMandateReference> for diesel_models::PayoutsMandateReference {
fn from(value: PayoutsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v1")]
impl From<diesel_models::PaymentsMandateReference> for PaymentsMandateReference {
fn from(value: diesel_models::PaymentsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReference> for diesel_models::PaymentsMandateReference {
fn from(value: PaymentsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v2")]
impl From<diesel_models::PaymentsTokenReference> for PaymentsTokenReference {
fn from(value: diesel_models::PaymentsTokenReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v2")]
impl From<PaymentsTokenReference> for diesel_models::PaymentsTokenReference {
fn from(value: PaymentsTokenReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
impl From<diesel_models::PayoutsMandateReferenceRecord> for PayoutsMandateReferenceRecord {
fn from(value: diesel_models::PayoutsMandateReferenceRecord) -> Self {
Self {
transfer_method_id: value.transfer_method_id,
}
}
}
impl From<PayoutsMandateReferenceRecord> for diesel_models::PayoutsMandateReferenceRecord {
fn from(value: PayoutsMandateReferenceRecord) -> Self {
Self {
transfer_method_id: value.transfer_method_id,
}
}
}
#[cfg(feature = "v2")]
impl From<diesel_models::ConnectorTokenReferenceRecord> for ConnectorTokenReferenceRecord {
fn from(value: diesel_models::ConnectorTokenReferenceRecord) -> Self {
let diesel_models::ConnectorTokenReferenceRecord {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
} = value;
Self {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v1")]
impl From<diesel_models::PaymentsMandateReferenceRecord> for PaymentsMandateReferenceRecord {
fn from(value: diesel_models::PaymentsMandateReferenceRecord) -> Self {
Self {
connector_mandate_id: value.connector_mandate_id,
payment_method_type: value.payment_method_type,
original_payment_authorized_amount: value.original_payment_authorized_amount,
original_payment_authorized_currency: value.original_payment_authorized_currency,
mandate_metadata: value.mandate_metadata,
connector_mandate_status: value.connector_mandate_status,
connector_mandate_request_reference_id: value.connector_mandate_request_reference_id,
}
}
}
#[cfg(feature = "v2")]
impl From<ConnectorTokenReferenceRecord> for diesel_models::ConnectorTokenReferenceRecord {
fn from(value: ConnectorTokenReferenceRecord) -> Self {
let ConnectorTokenReferenceRecord {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
} = value;
Self {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReferenceRecord> for diesel_models::PaymentsMandateReferenceRecord {
fn from(value: PaymentsMandateReferenceRecord) -> Self {
Self {
connector_mandate_id: value.connector_mandate_id,
payment_method_type: value.payment_method_type,
original_payment_authorized_amount: value.original_payment_authorized_amount,
original_payment_authorized_currency: value.original_payment_authorized_currency,
mandate_metadata: value.mandate_metadata,
connector_mandate_status: value.connector_mandate_status,
connector_mandate_request_reference_id: value.connector_mandate_request_reference_id,
}
}
}
| 4,506 | 2,393 |
hyperswitch | crates/hyperswitch_domain_models/src/routing.rs | .rs | use std::collections::HashMap;
use api_models::{enums as api_enums, routing};
use serde;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingData {
pub routed_through: Option<String>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: PaymentRoutingInfo,
pub algorithm: Option<routing::StraightThroughAlgorithm>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(from = "PaymentRoutingInfoSerde", into = "PaymentRoutingInfoSerde")]
pub struct PaymentRoutingInfo {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(untagged)]
pub enum PreRoutingConnectorChoice {
Single(routing::RoutableConnectorChoice),
Multiple(Vec<routing::RoutableConnectorChoice>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentRoutingInfoInner {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum PaymentRoutingInfoSerde {
OnlyAlgorithm(Box<routing::StraightThroughAlgorithm>),
WithDetails(Box<PaymentRoutingInfoInner>),
}
impl From<PaymentRoutingInfoSerde> for PaymentRoutingInfo {
fn from(value: PaymentRoutingInfoSerde) -> Self {
match value {
PaymentRoutingInfoSerde::OnlyAlgorithm(algo) => Self {
algorithm: Some(*algo),
pre_routing_results: None,
},
PaymentRoutingInfoSerde::WithDetails(details) => Self {
algorithm: details.algorithm,
pre_routing_results: details.pre_routing_results,
},
}
}
}
impl From<PaymentRoutingInfo> for PaymentRoutingInfoSerde {
fn from(value: PaymentRoutingInfo) -> Self {
Self::WithDetails(Box::new(PaymentRoutingInfoInner {
algorithm: value.algorithm,
pre_routing_results: value.pre_routing_results,
}))
}
}
| 491 | 2,394 |
hyperswitch | crates/hyperswitch_domain_models/src/customer.rs | .rs | #[cfg(all(feature = "v2", feature = "customer_v2"))]
use common_enums::DeleteStatus;
use common_utils::{
crypto::{self, Encryptable},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii,
types::{
keymanager::{self, KeyManagerState, ToEncryptable},
Description,
},
};
use diesel_models::customers::CustomerUpdateInternal;
use error_stack::ResultExt;
use masking::{PeekInterface, Secret, SwitchStrategy};
use rustc_hash::FxHashMap;
use time::PrimitiveDateTime;
use crate::type_encryption as types;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub address_id: Option<String>,
pub default_payment_method_id: Option<String>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub merchant_reference_id: Option<id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub id: id_type::GlobalCustomerId,
pub version: common_enums::ApiVersion,
pub status: DeleteStatus,
}
impl Customer {
/// Get the unique identifier of Customer
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
pub fn get_id(&self) -> &id_type::CustomerId {
&self.customer_id
}
/// Get the global identifier of Customer
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub fn get_id(&self) -> &id_type::GlobalCustomerId {
&self.id
}
/// Get the connector customer ID for the specified connector label, if present
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> {
use masking::PeekInterface;
self.connector_customer
.as_ref()
.and_then(|connector_customer_value| {
connector_customer_value.peek().get(connector_label)
})
.and_then(|connector_customer| connector_customer.as_str())
}
/// Get the connector customer ID for the specified merchant connector account ID, if present
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub fn get_connector_customer_id(
&self,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
) -> Option<&str> {
self.connector_customer
.as_ref()
.and_then(|connector_customer_map| connector_customer_map.get(merchant_connector_id))
.map(|connector_customer_id| connector_customer_id.as_str())
}
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[async_trait::async_trait]
impl super::behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
address_id: self.address_id,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
version: self.version,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
address_id: item.address_id,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
version: item.version,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
address_id: self.address_id,
updated_by: self.updated_by,
version: self.version,
})
}
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[async_trait::async_trait]
impl super::behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: self.version,
status: self.status,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
id: item.id,
merchant_reference_id: item.merchant_reference_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
default_billing_address: item.default_billing_address,
default_shipping_address: item.default_shipping_address,
version: item.version,
status: item.status,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
default_payment_method_id: None,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: common_types::consts::API_VERSION,
status: self.status,
})
}
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[derive(Clone, Debug)]
pub struct CustomerGeneralUpdate {
pub name: crypto::OptionalEncryptableName,
pub email: Box<crypto::OptionalEncryptableEmail>,
pub phone: Box<crypto::OptionalEncryptablePhone>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
pub status: Option<DeleteStatus>,
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update(Box<CustomerGeneralUpdate>),
ConnectorCustomer {
connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
},
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update(update) => {
let CustomerGeneralUpdate {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
default_billing_address,
default_shipping_address,
default_payment_method_id,
status,
} = *update;
Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
default_billing_address,
default_shipping_address,
default_payment_method_id,
updated_by: None,
status,
}
}
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
modified_at: date_time::now(),
default_payment_method_id: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
},
}
}
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update {
name: crypto::OptionalEncryptableName,
email: crypto::OptionalEncryptableEmail,
phone: Box<crypto::OptionalEncryptablePhone>,
description: Option<Description>,
phone_country_code: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
connector_customer: Box<Option<pii::SecretSerdeValue>>,
address_id: Option<String>,
},
ConnectorCustomer {
connector_customer: Option<pii::SecretSerdeValue>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<String>>,
},
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
} => Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
address_id,
default_payment_method_id: None,
updated_by: None,
},
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
default_payment_method_id: None,
updated_by: None,
address_id: None,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
address_id: None,
},
}
}
}
| 3,787 | 2,395 |
hyperswitch | crates/hyperswitch_domain_models/src/revenue_recovery.rs | .rs | use api_models::{payments as api_payments, webhooks};
use common_enums::enums as common_enums;
use common_utils::{id_type, types as util_types};
use time::PrimitiveDateTime;
use crate::router_response_types::revenue_recovery::BillingConnectorPaymentsSyncResponse;
/// Recovery payload is unified struct constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryAttemptData {
/// transaction amount against invoice, accepted in minor unit.
pub amount: util_types::MinorUnit,
/// currency of the transaction
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// transaction id reference at payment connector
pub connector_transaction_id: Option<util_types::ConnectorTransactionId>,
/// error code sent by billing connector.
pub error_code: Option<String>,
/// error message sent by billing connector.
pub error_message: Option<String>,
/// mandate token at payment processor end.
pub processor_payment_method_token: String,
/// customer id at payment connector for which mandate is attached.
pub connector_customer_id: String,
/// Payment gateway identifier id at billing processor.
pub connector_account_reference_id: String,
/// timestamp at which transaction has been created at billing connector
pub transaction_created_at: Option<PrimitiveDateTime>,
/// transaction status at billing connector equivalent to payment attempt status.
pub status: common_enums::AttemptStatus,
/// payment method of payment attempt.
pub payment_method_type: common_enums::PaymentMethod,
/// payment method sub type of the payment attempt.
pub payment_method_sub_type: common_enums::PaymentMethodType,
/// This field can be returned for both approved and refused Mastercard payments.
/// This code provides additional information about the type of transaction or the reason why the payment failed.
/// If the payment failed, the network advice code gives guidance on if and when you can retry the payment.
pub network_advice_code: Option<String>,
/// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.
pub network_decline_code: Option<String>,
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
}
/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryInvoiceData {
/// invoice amount at billing connector
pub amount: util_types::MinorUnit,
/// currency of the amount.
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
}
/// type of action that needs to taken after consuming recovery payload
#[derive(Debug)]
pub enum RecoveryAction {
/// Stops the process tracker and update the payment intent.
CancelInvoice,
/// Records the external transaction against payment intent.
ScheduleFailedPayment,
/// Records the external payment and stops the internal process tracker.
SuccessPaymentExternal,
/// Pending payments from billing processor.
PendingPayment,
/// No action required.
NoAction,
/// Invalid event has been received.
InvalidAction,
}
pub struct RecoveryPaymentIntent {
pub payment_id: id_type::GlobalPaymentId,
pub status: common_enums::IntentStatus,
pub feature_metadata: Option<api_payments::FeatureMetadata>,
}
pub struct RecoveryPaymentAttempt {
pub attempt_id: id_type::GlobalAttemptId,
pub attempt_status: common_enums::AttemptStatus,
pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>,
}
impl RecoveryPaymentAttempt {
pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata
.revenue_recovery
.as_ref()
.map(|recovery| recovery.attempt_triggered_by)
})
}
}
impl RecoveryAction {
pub fn get_action(
event_type: webhooks::IncomingWebhookEvent,
attempt_triggered_by: Option<common_enums::TriggeredBy>,
) -> Self {
match event_type {
webhooks::IncomingWebhookEvent::PaymentIntentFailure
| webhooks::IncomingWebhookEvent::PaymentIntentSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentProcessing
| webhooks::IncomingWebhookEvent::PaymentIntentPartiallyFunded
| webhooks::IncomingWebhookEvent::PaymentIntentCancelled
| webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure
| webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure
| webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure
| webhooks::IncomingWebhookEvent::PaymentActionRequired
| webhooks::IncomingWebhookEvent::EventNotSupported
| webhooks::IncomingWebhookEvent::SourceChargeable
| webhooks::IncomingWebhookEvent::SourceTransactionCreated
| webhooks::IncomingWebhookEvent::RefundFailure
| webhooks::IncomingWebhookEvent::RefundSuccess
| webhooks::IncomingWebhookEvent::DisputeOpened
| webhooks::IncomingWebhookEvent::DisputeExpired
| webhooks::IncomingWebhookEvent::DisputeAccepted
| webhooks::IncomingWebhookEvent::DisputeCancelled
| webhooks::IncomingWebhookEvent::DisputeChallenged
| webhooks::IncomingWebhookEvent::DisputeWon
| webhooks::IncomingWebhookEvent::DisputeLost
| webhooks::IncomingWebhookEvent::MandateActive
| webhooks::IncomingWebhookEvent::MandateRevoked
| webhooks::IncomingWebhookEvent::EndpointVerification
| webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
| webhooks::IncomingWebhookEvent::FrmApproved
| webhooks::IncomingWebhookEvent::FrmRejected
| webhooks::IncomingWebhookEvent::PayoutSuccess
| webhooks::IncomingWebhookEvent::PayoutFailure
| webhooks::IncomingWebhookEvent::PayoutProcessing
| webhooks::IncomingWebhookEvent::PayoutCancelled
| webhooks::IncomingWebhookEvent::PayoutCreated
| webhooks::IncomingWebhookEvent::PayoutExpired
| webhooks::IncomingWebhookEvent::PayoutReversed => Self::InvalidAction,
webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by {
Some(common_enums::TriggeredBy::Internal) => Self::NoAction,
Some(common_enums::TriggeredBy::External) | None => Self::ScheduleFailedPayment,
},
webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess => match attempt_triggered_by {
Some(common_enums::TriggeredBy::Internal) => Self::NoAction,
Some(common_enums::TriggeredBy::External) | None => Self::SuccessPaymentExternal,
},
webhooks::IncomingWebhookEvent::RecoveryPaymentPending => Self::PendingPayment,
webhooks::IncomingWebhookEvent::RecoveryInvoiceCancel => Self::CancelInvoice,
}
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount = api_payments::AmountDetailsSetter {
order_amount: data.amount.into(),
currency: data.currency,
shipping_cost: None,
order_tax_amount: None,
skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip,
skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip,
surcharge_amount: None,
tax_on_surcharge: None,
};
Self::new(amount)
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount_details = api_payments::AmountDetails::from(data);
Self {
amount_details,
merchant_reference_id: Some(data.merchant_reference_id.clone()),
routing_algorithm_id: None,
// Payments in the revenue recovery flow are always recurring transactions,
// so capture method will be always automatic.
capture_method: Some(common_enums::CaptureMethod::Automatic),
authentication_type: Some(common_enums::AuthenticationType::NoThreeDs),
billing: None,
shipping: None,
customer_id: None,
customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent),
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_enabled: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
force_3ds_challenge: None,
}
}
}
impl From<&BillingConnectorPaymentsSyncResponse> for RevenueRecoveryInvoiceData {
fn from(data: &BillingConnectorPaymentsSyncResponse) -> Self {
Self {
amount: data.amount,
currency: data.currency,
merchant_reference_id: data.merchant_reference_id.clone(),
}
}
}
impl From<&BillingConnectorPaymentsSyncResponse> for RevenueRecoveryAttemptData {
fn from(data: &BillingConnectorPaymentsSyncResponse) -> Self {
Self {
amount: data.amount,
currency: data.currency,
merchant_reference_id: data.merchant_reference_id.clone(),
connector_transaction_id: data.connector_transaction_id.clone(),
error_code: data.error_code.clone(),
error_message: data.error_message.clone(),
processor_payment_method_token: data.processor_payment_method_token.clone(),
connector_customer_id: data.connector_customer_id.clone(),
connector_account_reference_id: data.connector_account_reference_id.clone(),
transaction_created_at: data.transaction_created_at,
status: data.status,
payment_method_type: data.payment_method_type,
payment_method_sub_type: data.payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
}
}
impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
Self {
net_amount: data.amount,
amount_to_capture: None,
surcharge_amount: None,
tax_on_surcharge: None,
amount_capturable: data.amount,
shipping_cost: None,
order_tax_amount: None,
}
}
}
impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
data.error_code
.as_ref()
.zip(data.error_message.clone())
.map(|(code, message)| api_payments::RecordAttemptErrorDetails {
code: code.to_string(),
message: message.to_string(),
network_advice_code: data.network_advice_code.clone(),
network_decline_code: data.network_decline_code.clone(),
network_error_message: data.network_error_message.clone(),
})
}
}
| 2,482 | 2,396 |
hyperswitch | crates/hyperswitch_domain_models/src/router_response_types.rs | .rs | pub mod disputes;
pub mod fraud_check;
pub mod revenue_recovery;
use std::collections::HashMap;
use common_utils::{request::Method, types::MinorUnit};
pub use disputes::{AcceptDisputeResponse, DefendDisputeResponse, SubmitEvidenceResponse};
use crate::{
errors::api_error_response::ApiErrorResponse,
router_request_types::{authentication::AuthNFlowType, ResponseId},
};
#[derive(Debug, Clone)]
pub struct RefundsResponseData {
pub connector_refund_id: String,
pub refund_status: common_enums::RefundStatus,
// pub amount_received: Option<i32>, // Calculation for amount received not in place yet
}
#[derive(Debug, Clone)]
pub enum PaymentsResponseData {
TransactionResponse {
resource_id: ResponseId,
redirection_data: Box<Option<RedirectForm>>,
mandate_reference: Box<Option<MandateReference>>,
connector_metadata: Option<serde_json::Value>,
network_txn_id: Option<String>,
connector_response_reference_id: Option<String>,
incremental_authorization_allowed: Option<bool>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
},
MultipleCaptureResponse {
// pending_capture_id_list: Vec<String>,
capture_sync_response_list: HashMap<String, CaptureSyncResponse>,
},
SessionResponse {
session_token: api_models::payments::SessionToken,
},
SessionTokenResponse {
session_token: String,
},
TransactionUnresolvedResponse {
resource_id: ResponseId,
//to add more info on cypto response, like `unresolved` reason(overpaid, underpaid, delayed)
reason: Option<api_models::enums::UnresolvedResponseReason>,
connector_response_reference_id: Option<String>,
},
TokenizationResponse {
token: String,
},
ConnectorCustomerResponse {
connector_customer_id: String,
},
ThreeDSEnrollmentResponse {
enrolled_v2: bool,
related_transaction_id: Option<String>,
},
PreProcessingResponse {
pre_processing_id: PreprocessingResponseId,
connector_metadata: Option<serde_json::Value>,
session_token: Option<api_models::payments::SessionToken>,
connector_response_reference_id: Option<String>,
},
IncrementalAuthorizationResponse {
status: common_enums::AuthorizationStatus,
connector_authorization_id: Option<String>,
error_code: Option<String>,
error_message: Option<String>,
},
PostProcessingResponse {
session_token: Option<api_models::payments::OpenBankingSessionToken>,
},
SessionUpdateResponse {
status: common_enums::SessionUpdateStatus,
},
}
#[derive(Debug, Clone)]
pub struct TaxCalculationResponseData {
pub order_tax_amount: MinorUnit,
}
#[derive(serde::Serialize, Debug, Clone)]
pub struct MandateReference {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>,
pub connector_mandate_request_reference_id: Option<String>,
}
#[derive(Debug, Clone)]
pub enum CaptureSyncResponse {
Success {
resource_id: ResponseId,
status: common_enums::AttemptStatus,
connector_response_reference_id: Option<String>,
amount: Option<MinorUnit>,
},
Error {
code: String,
message: String,
reason: Option<String>,
status_code: u16,
amount: Option<MinorUnit>,
},
}
impl CaptureSyncResponse {
pub fn get_amount_captured(&self) -> Option<MinorUnit> {
match self {
Self::Success { amount, .. } | Self::Error { amount, .. } => *amount,
}
}
pub fn get_connector_response_reference_id(&self) -> Option<String> {
match self {
Self::Success {
connector_response_reference_id,
..
} => connector_response_reference_id.clone(),
Self::Error { .. } => None,
}
}
}
impl PaymentsResponseData {
pub fn get_connector_metadata(&self) -> Option<masking::Secret<serde_json::Value>> {
match self {
Self::TransactionResponse {
connector_metadata, ..
}
| Self::PreProcessingResponse {
connector_metadata, ..
} => connector_metadata.clone().map(masking::Secret::new),
_ => None,
}
}
pub fn get_connector_transaction_id(
&self,
) -> Result<String, error_stack::Report<ApiErrorResponse>> {
match self {
Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id),
..
} => Ok(txn_id.to_string()),
_ => Err(ApiErrorResponse::MissingRequiredField {
field_name: "ConnectorTransactionId",
}
.into()),
}
}
pub fn merge_transaction_responses(
auth_response: &Self,
capture_response: &Self,
) -> Result<Self, error_stack::Report<ApiErrorResponse>> {
match (auth_response, capture_response) {
(
Self::TransactionResponse {
resource_id: _,
redirection_data: auth_redirection_data,
mandate_reference: auth_mandate_reference,
connector_metadata: auth_connector_metadata,
network_txn_id: auth_network_txn_id,
connector_response_reference_id: auth_connector_response_reference_id,
incremental_authorization_allowed: auth_incremental_auth_allowed,
charges: auth_charges,
},
Self::TransactionResponse {
resource_id: capture_resource_id,
redirection_data: capture_redirection_data,
mandate_reference: capture_mandate_reference,
connector_metadata: capture_connector_metadata,
network_txn_id: capture_network_txn_id,
connector_response_reference_id: capture_connector_response_reference_id,
incremental_authorization_allowed: capture_incremental_auth_allowed,
charges: capture_charges,
},
) => Ok(Self::TransactionResponse {
resource_id: capture_resource_id.clone(),
redirection_data: Box::new(
capture_redirection_data
.clone()
.or_else(|| *auth_redirection_data.clone()),
),
mandate_reference: Box::new(
auth_mandate_reference
.clone()
.or_else(|| *capture_mandate_reference.clone()),
),
connector_metadata: capture_connector_metadata
.clone()
.or(auth_connector_metadata.clone()),
network_txn_id: capture_network_txn_id
.clone()
.or(auth_network_txn_id.clone()),
connector_response_reference_id: capture_connector_response_reference_id
.clone()
.or(auth_connector_response_reference_id.clone()),
incremental_authorization_allowed: (*capture_incremental_auth_allowed)
.or(*auth_incremental_auth_allowed),
charges: auth_charges.clone().or(capture_charges.clone()),
}),
_ => Err(ApiErrorResponse::NotSupported {
message: "Invalid Flow ".to_owned(),
}
.into()),
}
}
#[cfg(feature = "v2")]
pub fn get_updated_connector_token_details(
&self,
original_connector_mandate_request_reference_id: Option<String>,
) -> Option<diesel_models::ConnectorTokenDetails> {
if let Self::TransactionResponse {
mandate_reference, ..
} = self
{
mandate_reference.clone().map(|mandate_ref| {
let connector_mandate_id = mandate_ref.connector_mandate_id;
let connector_mandate_request_reference_id = mandate_ref
.connector_mandate_request_reference_id
.or(original_connector_mandate_request_reference_id);
diesel_models::ConnectorTokenDetails {
connector_mandate_id,
connector_token_request_reference_id: connector_mandate_request_reference_id,
}
})
} else {
None
}
}
}
#[derive(Debug, Clone)]
pub enum PreprocessingResponseId {
PreProcessingId(String),
ConnectorTransactionId(String),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub enum RedirectForm {
Form {
endpoint: String,
method: Method,
form_fields: HashMap<String, String>,
},
Html {
html_data: String,
},
BlueSnap {
payment_fields_token: String, // payment-field-token
},
CybersourceAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
CybersourceConsumerAuth {
access_token: String,
step_up_url: String,
},
DeutschebankThreeDSChallengeFlow {
acs_url: String,
creq: String,
},
Payme,
Braintree {
client_token: String,
card_token: String,
bin: String,
acs_url: String,
},
Nmi {
amount: String,
currency: common_enums::Currency,
public_key: masking::Secret<String>,
customer_vault_id: String,
order_id: String,
},
Mifinity {
initialization_token: String,
},
WorldpayDDCForm {
endpoint: url::Url,
method: Method,
form_fields: HashMap<String, String>,
collection_id: Option<String>,
},
}
impl From<(url::Url, Method)> for RedirectForm {
fn from((mut redirect_url, method): (url::Url, Method)) -> Self {
let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Self::Form {
endpoint: redirect_url.to_string(),
method,
form_fields,
}
}
}
impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm {
fn from(redirect_form: RedirectForm) -> Self {
match redirect_form {
RedirectForm::Form {
endpoint,
method,
form_fields,
} => Self::Form {
endpoint,
method,
form_fields,
},
RedirectForm::Html { html_data } => Self::Html { html_data },
RedirectForm::BlueSnap {
payment_fields_token,
} => Self::BlueSnap {
payment_fields_token,
},
RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
},
RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => Self::CybersourceConsumerAuth {
access_token,
step_up_url,
},
RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
Self::DeutschebankThreeDSChallengeFlow { acs_url, creq }
}
RedirectForm::Payme => Self::Payme,
RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => Self::Braintree {
client_token,
card_token,
bin,
acs_url,
},
RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => Self::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
},
RedirectForm::Mifinity {
initialization_token,
} => Self::Mifinity {
initialization_token,
},
RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => Self::WorldpayDDCForm {
endpoint: common_utils::types::Url::wrap(endpoint),
method,
form_fields,
collection_id,
},
}
}
}
impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm {
fn from(redirect_form: diesel_models::payment_attempt::RedirectForm) -> Self {
match redirect_form {
diesel_models::payment_attempt::RedirectForm::Form {
endpoint,
method,
form_fields,
} => Self::Form {
endpoint,
method,
form_fields,
},
diesel_models::payment_attempt::RedirectForm::Html { html_data } => {
Self::Html { html_data }
}
diesel_models::payment_attempt::RedirectForm::BlueSnap {
payment_fields_token,
} => Self::BlueSnap {
payment_fields_token,
},
diesel_models::payment_attempt::RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
},
diesel_models::payment_attempt::RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => Self::CybersourceConsumerAuth {
access_token,
step_up_url,
},
diesel_models::RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
Self::DeutschebankThreeDSChallengeFlow { acs_url, creq }
}
diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme,
diesel_models::payment_attempt::RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => Self::Braintree {
client_token,
card_token,
bin,
acs_url,
},
diesel_models::payment_attempt::RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => Self::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
},
diesel_models::payment_attempt::RedirectForm::Mifinity {
initialization_token,
} => Self::Mifinity {
initialization_token,
},
diesel_models::payment_attempt::RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => Self::WorldpayDDCForm {
endpoint: endpoint.into_inner(),
method,
form_fields,
collection_id,
},
}
}
}
#[derive(Default, Clone, Debug)]
pub struct UploadFileResponse {
pub provider_file_id: String,
}
#[derive(Clone, Debug)]
pub struct RetrieveFileResponse {
pub file_data: Vec<u8>,
}
#[cfg(feature = "payouts")]
#[derive(Clone, Debug, Default)]
pub struct PayoutsResponseData {
pub status: Option<common_enums::PayoutStatus>,
pub connector_payout_id: Option<String>,
pub payout_eligible: Option<bool>,
pub should_add_next_step_to_process_tracker: bool,
pub error_code: Option<String>,
pub error_message: Option<String>,
}
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceResponseData {
pub verify_webhook_status: VerifyWebhookStatus,
}
#[derive(Debug, Clone)]
pub enum VerifyWebhookStatus {
SourceVerified,
SourceNotVerified,
}
#[derive(Debug, Clone)]
pub struct MandateRevokeResponseData {
pub mandate_status: common_enums::MandateStatus,
}
#[derive(Debug, Clone)]
pub enum AuthenticationResponseData {
PreAuthVersionCallResponse {
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
},
PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
connector_metadata: Option<serde_json::Value>,
},
PreAuthNResponse {
threeds_server_transaction_id: String,
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
connector_authentication_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
message_version: common_utils::types::SemanticVersion,
connector_metadata: Option<serde_json::Value>,
directory_server_id: Option<String>,
},
AuthNResponse {
authn_flow_type: AuthNFlowType,
authentication_value: Option<String>,
trans_status: common_enums::TransactionStatus,
connector_metadata: Option<serde_json::Value>,
ds_trans_id: Option<String>,
},
PostAuthNResponse {
trans_status: common_enums::TransactionStatus,
authentication_value: Option<String>,
eci: Option<String>,
},
}
#[derive(Debug, Clone)]
pub struct CompleteAuthorizeRedirectResponse {
pub params: Option<masking::Secret<String>>,
pub payload: Option<common_utils::pii::SecretSerdeValue>,
}
/// Represents details of a payment method.
#[derive(Debug, Clone)]
pub struct PaymentMethodDetails {
/// Indicates whether mandates are supported by this payment method.
pub mandates: common_enums::FeatureStatus,
/// Indicates whether refund is supported by this payment method.
pub refunds: common_enums::FeatureStatus,
/// List of supported capture methods
pub supported_capture_methods: Vec<common_enums::CaptureMethod>,
/// Payment method specific features
pub specific_features: Option<api_models::feature_matrix::PaymentMethodSpecificFeatures>,
}
/// list of payment method types and metadata related to them
pub type PaymentMethodTypeMetadata = HashMap<common_enums::PaymentMethodType, PaymentMethodDetails>;
/// list of payment methods, payment method types and metadata related to them
pub type SupportedPaymentMethods = HashMap<common_enums::PaymentMethod, PaymentMethodTypeMetadata>;
#[derive(Debug, Clone)]
pub struct ConnectorInfo {
/// Display name of the Connector
pub display_name: &'static str,
/// Description of the connector.
pub description: &'static str,
/// Connector Type
pub connector_type: common_enums::PaymentConnectorCategory,
}
pub trait SupportedPaymentMethodsExt {
fn add(
&mut self,
payment_method: common_enums::PaymentMethod,
payment_method_type: common_enums::PaymentMethodType,
payment_method_details: PaymentMethodDetails,
);
}
impl SupportedPaymentMethodsExt for SupportedPaymentMethods {
fn add(
&mut self,
payment_method: common_enums::PaymentMethod,
payment_method_type: common_enums::PaymentMethodType,
payment_method_details: PaymentMethodDetails,
) {
if let Some(payment_method_data) = self.get_mut(&payment_method) {
payment_method_data.insert(payment_method_type, payment_method_details);
} else {
let mut payment_method_type_metadata = PaymentMethodTypeMetadata::new();
payment_method_type_metadata.insert(payment_method_type, payment_method_details);
self.insert(payment_method, payment_method_type_metadata);
}
}
}
| 3,980 | 2,397 |
hyperswitch | crates/hyperswitch_domain_models/src/payment_address.rs | .rs | use crate::address::Address;
#[derive(Clone, Default, Debug)]
pub struct PaymentAddress {
shipping: Option<Address>,
billing: Option<Address>,
unified_payment_method_billing: Option<Address>,
payment_method_billing: Option<Address>,
}
impl PaymentAddress {
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self {
// billing -> .billing, this is the billing details passed in the root of payments request
// payment_method_billing -> .payment_method_data.billing
let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
// Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
// The unified payment_method_billing will be used as billing address and passed to the connector module
// This unification is required in order to provide backwards compatibility
// so that if `payment.billing` is passed it should be sent to the connector module
// Unify the billing details with `payment_method_data.billing`
payment_method_billing
.as_ref()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(billing.as_ref())
})
.or(billing.clone())
} else {
payment_method_billing.clone()
};
Self {
shipping,
billing,
unified_payment_method_billing,
payment_method_billing,
}
}
pub fn get_shipping(&self) -> Option<&Address> {
self.shipping.as_ref()
}
pub fn get_payment_method_billing(&self) -> Option<&Address> {
self.unified_payment_method_billing.as_ref()
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the fields passed in payment_method_data_billing takes precedence
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
) -> Self {
// Unify the billing details with `payment_method_data.billing_details`
let unified_payment_method_billing = payment_method_data_billing
.map(|payment_method_data_billing| {
payment_method_data_billing.unify_address(self.get_payment_method_billing())
})
.or(self.get_payment_method_billing().cloned());
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the `self` takes precedence
pub fn unify_with_payment_data_billing(
self,
other_payment_method_billing: Option<Address>,
) -> Self {
let unified_payment_method_billing = self
.get_payment_method_billing()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(other_payment_method_billing.as_ref())
})
.or(other_payment_method_billing);
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
pub fn get_payment_billing(&self) -> Option<&Address> {
self.billing.as_ref()
}
}
| 735 | 2,398 |
hyperswitch | crates/hyperswitch_domain_models/src/consts.rs | .rs | //! Constants that are used in the domain models.
use std::collections::HashSet;
use router_env::once_cell::sync::Lazy;
pub static ROUTING_ENABLED_PAYMENT_METHODS: Lazy<HashSet<common_enums::PaymentMethod>> =
Lazy::new(|| {
let mut set = HashSet::new();
set.insert(common_enums::PaymentMethod::BankTransfer);
set.insert(common_enums::PaymentMethod::BankDebit);
set.insert(common_enums::PaymentMethod::BankRedirect);
set
});
pub static ROUTING_ENABLED_PAYMENT_METHOD_TYPES: Lazy<HashSet<common_enums::PaymentMethodType>> =
Lazy::new(|| {
let mut set = HashSet::new();
set.insert(common_enums::PaymentMethodType::GooglePay);
set.insert(common_enums::PaymentMethodType::ApplePay);
set.insert(common_enums::PaymentMethodType::Klarna);
set.insert(common_enums::PaymentMethodType::Paypal);
set.insert(common_enums::PaymentMethodType::SamsungPay);
set
});
/// Length of the unique reference ID generated for connector mandate requests
pub const CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH: usize = 18;
| 253 | 2,399 |
hyperswitch | crates/hyperswitch_domain_models/src/refunds.rs | .rs | use crate::errors;
pub struct RefundListConstraints {
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub refund_id: Option<String>,
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub limit: Option<i64>,
pub offset: Option<i64>,
pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
pub currency: Option<Vec<common_enums::Currency>>,
pub refund_status: Option<Vec<common_enums::RefundStatus>>,
}
impl
TryFrom<(
api_models::refunds::RefundListRequest,
Option<Vec<common_utils::id_type::ProfileId>>,
)> for RefundListConstraints
{
type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
fn try_from(
(value, auth_profile_id_list): (
api_models::refunds::RefundListRequest,
Option<Vec<common_utils::id_type::ProfileId>>,
),
) -> Result<Self, Self::Error> {
let api_models::refunds::RefundListRequest {
connector,
currency,
refund_status,
payment_id,
refund_id,
profile_id,
limit,
offset,
time_range,
amount_filter,
merchant_connector_id,
} = value;
let profile_id_from_request_body = profile_id;
let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
(None, None) => None,
(None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
(Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
(Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
let profile_id_from_request_body_is_available_in_auth_profile_id_list =
auth_profile_id_list.contains(&profile_id_from_request_body);
if profile_id_from_request_body_is_available_in_auth_profile_id_list {
Some(vec![profile_id_from_request_body])
} else {
// This scenario is very unlikely to happen
return Err(error_stack::Report::new(
errors::api_error_response::ApiErrorResponse::PreconditionFailed {
message: format!(
"Access not available for the given profile_id {:?}",
profile_id_from_request_body
),
},
));
}
}
};
Ok(Self {
payment_id,
refund_id,
profile_id: profile_id_list,
limit,
offset,
time_range,
amount_filter,
connector,
merchant_connector_id,
currency,
refund_status,
})
}
}
| 607 | 2,400 |
hyperswitch | crates/hyperswitch_domain_models/src/router_request_types.rs | .rs | pub mod authentication;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod unified_authentication_service;
use api_models::payments::{AdditionalPaymentData, RequestSurchargeDetails};
use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit};
use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount};
use error_stack::ResultExt;
use masking::Secret;
use serde::Serialize;
use serde_with::serde_as;
use super::payment_method_data::PaymentMethodData;
use crate::{
address,
errors::api_error_response::ApiErrorResponse,
mandates, payments,
router_data::{self, RouterData},
router_flow_types as flows, router_response_types as response_types,
};
#[derive(Debug, Clone)]
pub struct PaymentsAuthorizeData {
pub payment_method_data: PaymentMethodData,
/// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
/// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
/// ```text
/// get_original_amount()
/// get_surcharge_amount()
/// get_tax_on_surcharge_amount()
/// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
/// ```
pub amount: i64,
pub order_tax_amount: Option<MinorUnit>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub customer_acceptance: Option<mandates::CustomerAcceptance>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub browser_info: Option<BrowserInformation>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub order_category: Option<String>,
pub session_token: Option<String>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub surcharge_details: Option<SurchargeDetails>,
pub customer_id: Option<id_type::CustomerId>,
pub request_incremental_authorization: bool,
pub metadata: Option<serde_json::Value>,
pub authentication_data: Option<AuthenticationData>,
pub request_extended_authorization:
Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<String>,
pub integrity_object: Option<AuthoriseIntegrityObject>,
pub shipping_cost: Option<MinorUnit>,
pub additional_payment_method_data: Option<AdditionalPaymentData>,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
}
#[derive(Debug, Clone)]
pub struct PaymentsPostSessionTokensData {
// amount here would include amount, surcharge_amount and shipping_cost
pub amount: MinorUnit,
/// original amount sent by the merchant
pub order_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub capture_method: Option<storage_enums::CaptureMethod>,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub router_return_url: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AuthoriseIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: storage_enums::Currency,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SyncIntegrityObject {
/// Sync amount
pub amount: Option<MinorUnit>,
/// Sync currency
pub currency: Option<storage_enums::Currency>,
}
#[derive(Debug, Clone, Default)]
pub struct PaymentsCaptureData {
pub amount_to_capture: i64,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub payment_amount: i64,
pub multiple_capture_data: Option<MultipleCaptureRequestData>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
pub capture_method: Option<storage_enums::CaptureMethod>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_payment_amount: MinorUnit,
pub minor_amount_to_capture: MinorUnit,
pub integrity_object: Option<CaptureIntegrityObject>,
pub webhook_url: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CaptureIntegrityObject {
/// capture amount
pub capture_amount: Option<MinorUnit>,
/// capture currency
pub currency: storage_enums::Currency,
}
#[derive(Debug, Clone, Default)]
pub struct PaymentsIncrementalAuthorizationData {
pub total_amount: i64,
pub additional_amount: i64,
pub currency: storage_enums::Currency,
pub reason: Option<String>,
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, Default)]
pub struct MultipleCaptureRequestData {
pub capture_sequence: i16,
pub capture_reference: String,
}
#[derive(Debug, Clone)]
pub struct AuthorizeSessionTokenData {
pub amount_to_capture: Option<i64>,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub amount: Option<i64>,
}
#[derive(Debug, Clone)]
pub struct ConnectorCustomerData {
pub description: Option<String>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub preprocessing_id: Option<String>,
pub payment_method_data: PaymentMethodData,
}
impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
email: data.email,
payment_method_data: data.payment_method_data,
description: None,
phone: None,
name: None,
preprocessing_id: None,
})
}
}
impl
TryFrom<
&RouterData<flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
> for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::Authorize,
PaymentsAuthorizeData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: data.request.payment_method_data.clone(),
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
})
}
}
#[derive(Debug, Clone)]
pub struct PaymentMethodTokenizationData {
pub payment_method_data: PaymentMethodData,
pub browser_info: Option<BrowserInformation>,
pub currency: storage_enums::Currency,
pub amount: Option<i64>,
}
impl TryFrom<SetupMandateRequestData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
browser_info: None,
currency: data.currency,
amount: data.amount,
})
}
}
impl<F> From<&RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>>
for PaymentMethodTokenizationData
{
fn from(
data: &RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
) -> Self {
Self {
payment_method_data: data.request.payment_method_data.clone(),
browser_info: None,
currency: data.request.currency,
amount: Some(data.request.amount),
}
}
}
impl TryFrom<PaymentsAuthorizeData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
browser_info: data.browser_info,
currency: data.currency,
amount: Some(data.amount),
})
}
}
impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data
.payment_method_data
.get_required_value("payment_method_data")
.change_context(ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
})?,
browser_info: data.browser_info,
currency: data.currency,
amount: Some(data.amount),
})
}
}
#[derive(Debug, Clone)]
pub struct PaymentsPreProcessingData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub surcharge_details: Option<SurchargeDetails>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub enrolled_for_3ds: bool,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub related_transaction_id: Option<String>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub metadata: Option<Secret<serde_json::Value>>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: data.order_details,
router_return_url: data.router_return_url,
webhook_url: data.webhook_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: data.surcharge_details,
connector_transaction_id: None,
mandate_id: data.mandate_id,
related_transaction_id: data.related_transaction_id,
redirect_response: None,
enrolled_for_3ds: data.enrolled_for_3ds,
split_payments: data.split_payments,
metadata: data.metadata.map(Secret::new),
})
}
}
impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: None,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: None,
connector_transaction_id: data.connector_transaction_id,
mandate_id: data.mandate_id,
related_transaction_id: None,
redirect_response: data.redirect_response,
split_payments: None,
enrolled_for_3ds: true,
metadata: data.connector_meta.map(Secret::new),
})
}
}
#[derive(Debug, Clone)]
pub struct PaymentsPostProcessingData {
pub payment_method_data: PaymentMethodData,
pub customer_id: Option<id_type::CustomerId>,
pub connector_transaction_id: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub header_payload: Option<payments::HeaderPayload>,
}
impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>>
for PaymentsPostProcessingData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.request.payment_method_data,
connector_transaction_id: match data.response {
Ok(response_types::PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(id),
..
}) => Some(id.clone()),
_ => None,
},
customer_id: data.request.customer_id,
country: data
.address
.get_payment_billing()
.and_then(|bl| bl.address.as_ref())
.and_then(|address| address.country),
connector_meta_data: data.connector_meta_data.clone(),
header_payload: data.header_payload,
})
}
}
#[derive(Debug, Clone)]
pub struct CompleteAuthorizeData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: i64,
pub email: Option<pii::Email>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub complete_authorize_url: Option<String>,
pub metadata: Option<serde_json::Value>,
pub customer_acceptance: Option<mandates::CustomerAcceptance>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>,
}
#[derive(Debug, Clone)]
pub struct CompleteAuthorizeRedirectResponse {
pub params: Option<Secret<String>>,
pub payload: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsSyncData {
//TODO : add fields based on the connector requirements
pub connector_transaction_id: ResponseId,
pub encoded_data: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub connector_meta: Option<serde_json::Value>,
pub sync_type: SyncRequestType,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub currency: storage_enums::Currency,
pub payment_experience: Option<common_enums::PaymentExperience>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub amount: MinorUnit,
pub integrity_object: Option<SyncIntegrityObject>,
}
#[derive(Debug, Default, Clone)]
pub enum SyncRequestType {
MultipleCaptureSync(Vec<String>),
#[default]
SinglePaymentSync,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsCancelData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
// minor amount data for amount framework
pub minor_amount: Option<MinorUnit>,
pub webhook_url: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsRejectData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsApproveData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
}
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct BrowserInformation {
pub color_depth: Option<u8>,
pub java_enabled: Option<bool>,
pub java_script_enabled: Option<bool>,
pub language: Option<String>,
pub screen_height: Option<u32>,
pub screen_width: Option<u32>,
pub time_zone: Option<i32>,
pub ip_address: Option<std::net::IpAddr>,
pub accept_header: Option<String>,
pub user_agent: Option<String>,
pub os_type: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub accept_language: Option<String>,
}
#[cfg(feature = "v2")]
impl From<common_utils::types::BrowserInformation> for BrowserInformation {
fn from(value: common_utils::types::BrowserInformation) -> Self {
Self {
color_depth: value.color_depth,
java_enabled: value.java_enabled,
java_script_enabled: value.java_script_enabled,
language: value.language,
screen_height: value.screen_height,
screen_width: value.screen_width,
time_zone: value.time_zone,
ip_address: value.ip_address,
accept_header: value.accept_header,
user_agent: value.user_agent,
os_type: value.os_type,
os_version: value.os_version,
device_model: value.device_model,
accept_language: value.accept_language,
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub enum ResponseId {
ConnectorTransactionId(String),
EncodedData(String),
#[default]
NoResponseId,
}
impl ResponseId {
pub fn get_connector_transaction_id(
&self,
) -> errors::CustomResult<String, errors::ValidationError> {
match self {
Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "connector_transaction_id",
})
.attach_printable("Expected connector transaction ID not found"),
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SurchargeDetails {
/// original_amount
pub original_amount: MinorUnit,
/// surcharge value
pub surcharge: common_utils::types::Surcharge,
/// tax on surcharge value
pub tax_on_surcharge:
Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
/// surcharge amount for this payment
pub surcharge_amount: MinorUnit,
/// tax on surcharge amount for this payment
pub tax_on_surcharge_amount: MinorUnit,
}
impl SurchargeDetails {
pub fn get_total_surcharge_amount(&self) -> MinorUnit {
self.surcharge_amount + self.tax_on_surcharge_amount
}
}
#[cfg(feature = "v1")]
impl
From<(
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
)> for SurchargeDetails
{
fn from(
(request_surcharge_details, payment_attempt): (
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
),
) -> Self {
let surcharge_amount = request_surcharge_details.surcharge_amount;
let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default();
Self {
original_amount: payment_attempt.net_amount.get_order_amount(),
surcharge: common_utils::types::Surcharge::Fixed(
request_surcharge_details.surcharge_amount,
),
tax_on_surcharge: None,
surcharge_amount,
tax_on_surcharge_amount,
}
}
}
#[cfg(feature = "v2")]
impl
From<(
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
)> for SurchargeDetails
{
fn from(
(request_surcharge_details, payment_attempt): (
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
),
) -> Self {
todo!()
}
}
#[derive(Debug, Clone)]
pub struct AuthenticationData {
pub eci: Option<String>,
pub cavv: String,
pub threeds_server_transaction_id: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub ds_trans_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct RefundsData {
pub refund_id: String,
pub connector_transaction_id: String,
pub connector_refund_id: Option<String>,
pub currency: storage_enums::Currency,
/// Amount for the payment against which this refund is issued
pub payment_amount: i64,
pub reason: Option<String>,
pub webhook_url: Option<String>,
/// Amount to be refunded
pub refund_amount: i64,
/// Arbitrary metadata required for refund
pub connector_metadata: Option<serde_json::Value>,
/// refund method
pub refund_connector_metadata: Option<pii::SecretSerdeValue>,
pub browser_info: Option<BrowserInformation>,
/// Charges associated with the payment
pub split_refunds: Option<SplitRefundsRequest>,
// New amount for amount frame work
pub minor_payment_amount: MinorUnit,
pub minor_refund_amount: MinorUnit,
pub integrity_object: Option<RefundIntegrityObject>,
pub refund_status: storage_enums::RefundStatus,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RefundIntegrityObject {
/// refund currency
pub currency: storage_enums::Currency,
/// refund amount
pub refund_amount: MinorUnit,
}
#[derive(Debug, serde::Deserialize, Clone)]
pub enum SplitRefundsRequest {
StripeSplitRefund(StripeSplitRefund),
AdyenSplitRefund(common_types::domain::AdyenSplitData),
XenditSplitRefund(common_types::domain::XenditSplitSubMerchantData),
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct StripeSplitRefund {
pub charge_id: String,
pub transfer_account_id: String,
pub charge_type: api_models::enums::PaymentChargeType,
pub options: ChargeRefundsOptions,
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct ChargeRefunds {
pub charge_id: String,
pub transfer_account_id: String,
pub charge_type: api_models::enums::PaymentChargeType,
pub options: ChargeRefundsOptions,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum ChargeRefundsOptions {
Destination(DestinationChargeRefund),
Direct(DirectChargeRefund),
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct DirectChargeRefund {
pub revert_platform_fee: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct DestinationChargeRefund {
pub revert_platform_fee: bool,
pub revert_transfer: bool,
}
#[derive(Debug, Clone)]
pub struct AccessTokenRequestData {
pub app_id: Secret<String>,
pub id: Option<Secret<String>>,
// Add more keys if required
}
impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData {
type Error = ApiErrorResponse;
fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> {
match connector_auth {
router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
app_id: api_key,
id: None,
}),
router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
app_id: api_key,
id: Some(key1),
}),
router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self {
app_id: api_key,
id: Some(key1),
}),
router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self {
app_id: api_key,
id: Some(key1),
}),
_ => Err(ApiErrorResponse::InvalidDataValue {
field_name: "connector_account_details",
}),
}
}
}
#[derive(Default, Debug, Clone)]
pub struct AcceptDisputeRequestData {
pub dispute_id: String,
pub connector_dispute_id: String,
}
#[derive(Default, Debug, Clone)]
pub struct DefendDisputeRequestData {
pub dispute_id: String,
pub connector_dispute_id: String,
}
#[derive(Default, Debug, Clone)]
pub struct SubmitEvidenceRequestData {
pub dispute_id: String,
pub connector_dispute_id: String,
pub access_activity_log: Option<String>,
pub billing_address: Option<String>,
//cancellation policy
pub cancellation_policy: Option<Vec<u8>>,
pub cancellation_policy_file_type: Option<String>,
pub cancellation_policy_provider_file_id: Option<String>,
pub cancellation_policy_disclosure: Option<String>,
pub cancellation_rebuttal: Option<String>,
//customer communication
pub customer_communication: Option<Vec<u8>>,
pub customer_communication_file_type: Option<String>,
pub customer_communication_provider_file_id: Option<String>,
pub customer_email_address: Option<String>,
pub customer_name: Option<String>,
pub customer_purchase_ip: Option<String>,
//customer signature
pub customer_signature: Option<Vec<u8>>,
pub customer_signature_file_type: Option<String>,
pub customer_signature_provider_file_id: Option<String>,
//product description
pub product_description: Option<String>,
//receipts
pub receipt: Option<Vec<u8>>,
pub receipt_file_type: Option<String>,
pub receipt_provider_file_id: Option<String>,
//refund policy
pub refund_policy: Option<Vec<u8>>,
pub refund_policy_file_type: Option<String>,
pub refund_policy_provider_file_id: Option<String>,
pub refund_policy_disclosure: Option<String>,
pub refund_refusal_explanation: Option<String>,
//service docs
pub service_date: Option<String>,
pub service_documentation: Option<Vec<u8>>,
pub service_documentation_file_type: Option<String>,
pub service_documentation_provider_file_id: Option<String>,
//shipping details docs
pub shipping_address: Option<String>,
pub shipping_carrier: Option<String>,
pub shipping_date: Option<String>,
pub shipping_documentation: Option<Vec<u8>>,
pub shipping_documentation_file_type: Option<String>,
pub shipping_documentation_provider_file_id: Option<String>,
pub shipping_tracking_number: Option<String>,
//invoice details
pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
pub invoice_showing_distinct_transactions_file_type: Option<String>,
pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
//subscription details
pub recurring_transaction_agreement: Option<Vec<u8>>,
pub recurring_transaction_agreement_file_type: Option<String>,
pub recurring_transaction_agreement_provider_file_id: Option<String>,
//uncategorized details
pub uncategorized_file: Option<Vec<u8>>,
pub uncategorized_file_type: Option<String>,
pub uncategorized_file_provider_file_id: Option<String>,
pub uncategorized_text: Option<String>,
}
#[derive(Clone, Debug)]
pub struct RetrieveFileRequestData {
pub provider_file_id: String,
}
#[serde_as]
#[derive(Clone, Debug, serde::Serialize)]
pub struct UploadFileRequestData {
pub file_key: String,
#[serde(skip)]
pub file: Vec<u8>,
#[serde_as(as = "serde_with::DisplayFromStr")]
pub file_type: mime::Mime,
pub file_size: i32,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone)]
pub struct PayoutsData {
pub payout_id: String,
pub amount: i64,
pub connector_payout_id: Option<String>,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub payout_type: Option<storage_enums::PayoutType>,
pub entity_type: storage_enums::PayoutEntityType,
pub customer_details: Option<CustomerDetails>,
pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>,
// New minor amount for amount framework
pub minor_amount: MinorUnit,
pub priority: Option<storage_enums::PayoutSendPriority>,
pub connector_transfer_method_id: Option<String>,
}
#[derive(Debug, Default, Clone)]
pub struct CustomerDetails {
pub customer_id: Option<id_type::CustomerId>,
pub name: Option<Secret<String, masking::WithType>>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String, masking::WithType>>,
pub phone_country_code: Option<String>,
}
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceRequestData {
pub webhook_headers: actix_web::http::header::HeaderMap,
pub webhook_body: Vec<u8>,
pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets,
}
#[derive(Debug, Clone)]
pub struct MandateRevokeRequestData {
pub mandate_id: String,
pub connector_mandate_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PaymentsSessionData {
pub amount: i64,
pub currency: common_enums::Currency,
pub country: Option<common_enums::CountryAlpha2>,
pub surcharge_details: Option<SurchargeDetails>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub email: Option<pii::Email>,
// Minor Unit amount for amount frame work
pub minor_amount: MinorUnit,
pub apple_pay_recurring_details: Option<api_models::payments::ApplePayRecurringPaymentRequest>,
}
#[derive(Debug, Clone, Default)]
pub struct PaymentsTaxCalculationData {
pub amount: MinorUnit,
pub currency: storage_enums::Currency,
pub shipping_cost: Option<MinorUnit>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub shipping_address: address::Address,
}
#[derive(Debug, Clone, Default)]
pub struct SdkPaymentsSessionUpdateData {
pub order_tax_amount: MinorUnit,
// amount here would include amount, surcharge_amount, order_tax_amount and shipping_cost
pub amount: MinorUnit,
/// original amount sent by the merchant
pub order_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub session_id: Option<String>,
pub shipping_cost: Option<MinorUnit>,
}
#[derive(Debug, Clone)]
pub struct SetupMandateRequestData {
pub currency: storage_enums::Currency,
pub payment_method_data: PaymentMethodData,
pub amount: Option<i64>,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub customer_acceptance: Option<mandates::CustomerAcceptance>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub return_url: Option<String>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub request_incremental_authorization: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub complete_authorize_url: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
// MinorUnit for amount framework
pub minor_amount: Option<MinorUnit>,
pub shipping_cost: Option<MinorUnit>,
}
| 7,429 | 2,401 |
hyperswitch | crates/hyperswitch_domain_models/src/types.rs | .rs | pub use diesel_models::types::OrderDetailsWithAmount;
use crate::{
router_data::{AccessToken, RouterData},
router_flow_types::{
mandate_revoke::MandateRevoke, revenue_recovery::RecoveryRecordBack, AccessTokenAuth,
Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken,
BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, Execute, IncrementalAuthorization, PSync, PaymentMethodToken,
PostAuthenticate, PostSessionTokens, PreAuthenticate, PreProcessing, RSync,
SdkSessionUpdate, Session, SetupMandate, VerifyWebhookSource, Void,
},
router_request_types::{
revenue_recovery::{BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest},
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData,
ConnectorCustomerData, MandateRevokeRequestData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
PaymentsTaxCalculationData, RefundsData, SdkPaymentsSessionUpdateData,
SetupMandateRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
revenue_recovery::{
BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse,
},
MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData,
TaxCalculationResponseData, VerifyWebhookSourceResponseData,
},
};
#[cfg(feature = "payouts")]
pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData};
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsAuthorizeSessionTokenRouterData =
RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>;
pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>;
pub type SetupMandateRouterData =
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>;
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>;
pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>;
pub type TokenizationRouterData =
RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>;
pub type ConnectorCustomerRouterData =
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>;
pub type PaymentsCompleteAuthorizeRouterData =
RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
pub type PaymentsTaxCalculationRouterData =
RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>;
pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
pub type PaymentsPostSessionTokensRouterData =
RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>;
pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>;
pub type UasPostAuthenticationRouterData =
RouterData<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>;
pub type UasPreAuthenticationRouterData =
RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>;
pub type UasAuthenticationConfirmationRouterData = RouterData<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>;
pub type MandateRevokeRouterData =
RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;
pub type PaymentsIncrementalAuthorizationRouterData = RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>;
pub type SdkSessionUpdateRouterData =
RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>;
pub type VerifyWebhookSourceRouterData = RouterData<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>;
#[cfg(feature = "payouts")]
pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
pub type RevenueRecoveryRecordBackRouterData = RouterData<
RecoveryRecordBack,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
>;
pub type UasAuthenticationRouterData =
RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>;
pub type BillingConnectorPaymentsSyncRouterData = RouterData<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>;
| 1,132 | 2,402 |
hyperswitch | crates/hyperswitch_domain_models/src/merchant_key_store.rs | .rs | use common_utils::{
crypto::Encryptable,
custom_serde, date_time,
errors::{CustomResult, ValidationError},
type_name,
types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::type_encryption::{crypto_operation, CryptoOperation};
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantKeyStore {
pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryptable<Secret<Vec<u8>>>,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantKeyStore {
type DstType = diesel_models::merchant_key_store::MerchantKeyStore;
type NewDstType = diesel_models::merchant_key_store::MerchantKeyStoreNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::merchant_key_store::MerchantKeyStore {
key: self.key.into(),
merchant_id: self.merchant_id,
created_at: self.created_at,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let identifier = keymanager::Identifier::Merchant(item.merchant_id.clone());
Ok(Self {
key: crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::Decrypt(item.key),
identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?,
merchant_id: item.merchant_id,
created_at: item.created_at,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::merchant_key_store::MerchantKeyStoreNew {
merchant_id: self.merchant_id,
key: self.key.into(),
created_at: date_time::now(),
})
}
}
| 503 | 2,403 |
hyperswitch | crates/hyperswitch_domain_models/src/lib.rs | .rs | pub mod address;
pub mod api;
pub mod behaviour;
pub mod bulk_tokenization;
pub mod business_profile;
pub mod callback_mapper;
pub mod card_testing_guard_data;
pub mod configs;
pub mod consts;
pub mod customer;
pub mod disputes;
pub mod errors;
pub mod mandates;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod network_tokenization;
pub mod payment_address;
pub mod payment_method_data;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod refunds;
pub mod relay;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
pub mod revenue_recovery;
pub mod router_data;
pub mod router_data_v2;
pub mod router_flow_types;
pub mod router_request_types;
pub mod router_response_types;
pub mod routing;
pub mod type_encryption;
pub mod types;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub mod vault;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
#[cfg(not(feature = "payouts"))]
pub trait PayoutsInterface {}
use api_models::payments::{
ApplePayRecurringDetails as ApiApplePayRecurringDetails,
ApplePayRegularBillingDetails as ApiApplePayRegularBillingDetails,
FeatureMetadata as ApiFeatureMetadata, OrderDetailsWithAmount as ApiOrderDetailsWithAmount,
RecurringPaymentIntervalUnit as ApiRecurringPaymentIntervalUnit,
RedirectResponse as ApiRedirectResponse,
};
#[cfg(feature = "v2")]
use api_models::payments::{
BillingConnectorPaymentDetails as ApiBillingConnectorPaymentDetails,
PaymentRevenueRecoveryMetadata as ApiRevenueRecoveryMetadata,
};
use diesel_models::types::{
ApplePayRecurringDetails, ApplePayRegularBillingDetails, FeatureMetadata,
OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse,
};
#[cfg(feature = "v2")]
use diesel_models::types::{BillingConnectorPaymentDetails, PaymentRevenueRecoveryMetadata};
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub enum RemoteStorageObject<T: ForeignIDRef> {
ForeignID(String),
Object(T),
}
impl<T: ForeignIDRef> From<T> for RemoteStorageObject<T> {
fn from(value: T) -> Self {
Self::Object(value)
}
}
pub trait ForeignIDRef {
fn foreign_id(&self) -> String;
}
impl<T: ForeignIDRef> RemoteStorageObject<T> {
pub fn get_id(&self) -> String {
match self {
Self::ForeignID(id) => id.clone(),
Self::Object(i) => i.foreign_id(),
}
}
}
use std::fmt::Debug;
pub trait ApiModelToDieselModelConvertor<F> {
/// Convert from a foreign type to the current type
fn convert_from(from: F) -> Self;
fn convert_back(self) -> F;
}
#[cfg(feature = "v1")]
impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {
fn convert_from(from: ApiFeatureMetadata) -> Self {
let ApiFeatureMetadata {
redirect_response,
search_tags,
apple_pay_recurring_details,
} = from;
Self {
redirect_response: redirect_response.map(RedirectResponse::convert_from),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(ApplePayRecurringDetails::convert_from),
}
}
fn convert_back(self) -> ApiFeatureMetadata {
let Self {
redirect_response,
search_tags,
apple_pay_recurring_details,
} = self;
ApiFeatureMetadata {
redirect_response: redirect_response
.map(|redirect_response| redirect_response.convert_back()),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(|value| value.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {
fn convert_from(from: ApiFeatureMetadata) -> Self {
let ApiFeatureMetadata {
redirect_response,
search_tags,
apple_pay_recurring_details,
payment_revenue_recovery_metadata,
} = from;
Self {
redirect_response: redirect_response.map(RedirectResponse::convert_from),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(ApplePayRecurringDetails::convert_from),
payment_revenue_recovery_metadata: payment_revenue_recovery_metadata
.map(PaymentRevenueRecoveryMetadata::convert_from),
}
}
fn convert_back(self) -> ApiFeatureMetadata {
let Self {
redirect_response,
search_tags,
apple_pay_recurring_details,
payment_revenue_recovery_metadata,
} = self;
ApiFeatureMetadata {
redirect_response: redirect_response
.map(|redirect_response| redirect_response.convert_back()),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(|value| value.convert_back()),
payment_revenue_recovery_metadata: payment_revenue_recovery_metadata
.map(|value| value.convert_back()),
}
}
}
impl ApiModelToDieselModelConvertor<ApiRedirectResponse> for RedirectResponse {
fn convert_from(from: ApiRedirectResponse) -> Self {
let ApiRedirectResponse {
param,
json_payload,
} = from;
Self {
param,
json_payload,
}
}
fn convert_back(self) -> ApiRedirectResponse {
let Self {
param,
json_payload,
} = self;
ApiRedirectResponse {
param,
json_payload,
}
}
}
impl ApiModelToDieselModelConvertor<ApiRecurringPaymentIntervalUnit>
for RecurringPaymentIntervalUnit
{
fn convert_from(from: ApiRecurringPaymentIntervalUnit) -> Self {
match from {
ApiRecurringPaymentIntervalUnit::Year => Self::Year,
ApiRecurringPaymentIntervalUnit::Month => Self::Month,
ApiRecurringPaymentIntervalUnit::Day => Self::Day,
ApiRecurringPaymentIntervalUnit::Hour => Self::Hour,
ApiRecurringPaymentIntervalUnit::Minute => Self::Minute,
}
}
fn convert_back(self) -> ApiRecurringPaymentIntervalUnit {
match self {
Self::Year => ApiRecurringPaymentIntervalUnit::Year,
Self::Month => ApiRecurringPaymentIntervalUnit::Month,
Self::Day => ApiRecurringPaymentIntervalUnit::Day,
Self::Hour => ApiRecurringPaymentIntervalUnit::Hour,
Self::Minute => ApiRecurringPaymentIntervalUnit::Minute,
}
}
}
impl ApiModelToDieselModelConvertor<ApiApplePayRegularBillingDetails>
for ApplePayRegularBillingDetails
{
fn convert_from(from: ApiApplePayRegularBillingDetails) -> Self {
Self {
label: from.label,
recurring_payment_start_date: from.recurring_payment_start_date,
recurring_payment_end_date: from.recurring_payment_end_date,
recurring_payment_interval_unit: from
.recurring_payment_interval_unit
.map(RecurringPaymentIntervalUnit::convert_from),
recurring_payment_interval_count: from.recurring_payment_interval_count,
}
}
fn convert_back(self) -> ApiApplePayRegularBillingDetails {
ApiApplePayRegularBillingDetails {
label: self.label,
recurring_payment_start_date: self.recurring_payment_start_date,
recurring_payment_end_date: self.recurring_payment_end_date,
recurring_payment_interval_unit: self
.recurring_payment_interval_unit
.map(|value| value.convert_back()),
recurring_payment_interval_count: self.recurring_payment_interval_count,
}
}
}
impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRecurringDetails {
fn convert_from(from: ApiApplePayRecurringDetails) -> Self {
Self {
payment_description: from.payment_description,
regular_billing: ApplePayRegularBillingDetails::convert_from(from.regular_billing),
billing_agreement: from.billing_agreement,
management_url: from.management_url,
}
}
fn convert_back(self) -> ApiApplePayRecurringDetails {
ApiApplePayRecurringDetails {
payment_description: self.payment_description,
regular_billing: self.regular_billing.convert_back(),
billing_agreement: self.billing_agreement,
management_url: self.management_url,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentRevenueRecoveryMetadata {
fn convert_from(from: ApiRevenueRecoveryMetadata) -> Self {
Self {
total_retry_count: from.total_retry_count,
payment_connector_transmission: from.payment_connector_transmission,
billing_connector_id: from.billing_connector_id,
active_attempt_payment_connector_id: from.active_attempt_payment_connector_id,
billing_connector_payment_details: BillingConnectorPaymentDetails::convert_from(
from.billing_connector_payment_details,
),
payment_method_type: from.payment_method_type,
payment_method_subtype: from.payment_method_subtype,
connector: from.connector,
}
}
fn convert_back(self) -> ApiRevenueRecoveryMetadata {
ApiRevenueRecoveryMetadata {
total_retry_count: self.total_retry_count,
payment_connector_transmission: self.payment_connector_transmission,
billing_connector_id: self.billing_connector_id,
active_attempt_payment_connector_id: self.active_attempt_payment_connector_id,
billing_connector_payment_details: self
.billing_connector_payment_details
.convert_back(),
payment_method_type: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
connector: self.connector,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentDetails>
for BillingConnectorPaymentDetails
{
fn convert_from(from: ApiBillingConnectorPaymentDetails) -> Self {
Self {
payment_processor_token: from.payment_processor_token,
connector_customer_id: from.connector_customer_id,
}
}
fn convert_back(self) -> ApiBillingConnectorPaymentDetails {
ApiBillingConnectorPaymentDetails {
payment_processor_token: self.payment_processor_token,
connector_customer_id: self.connector_customer_id,
}
}
}
impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsWithAmount {
fn convert_from(from: ApiOrderDetailsWithAmount) -> Self {
let ApiOrderDetailsWithAmount {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
} = from;
Self {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
}
}
fn convert_back(self) -> ApiOrderDetailsWithAmount {
let Self {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
} = self;
ApiOrderDetailsWithAmount {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
for diesel_models::payment_intent::PaymentLinkConfigRequestForPayments
{
fn convert_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self {
Self {
theme: item.theme,
logo: item.logo,
seller_name: item.seller_name,
sdk_layout: item.sdk_layout,
display_sdk_only: item.display_sdk_only,
enabled_saved_payment_method: item.enabled_saved_payment_method,
hide_card_nickname_field: item.hide_card_nickname_field,
show_card_form_by_default: item.show_card_form_by_default,
details_layout: item.details_layout,
transaction_details: item.transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| {
diesel_models::PaymentLinkTransactionDetails::convert_from(
transaction_detail,
)
})
.collect()
}),
background_image: item.background_image.map(|background_image| {
diesel_models::business_profile::PaymentLinkBackgroundImageConfig::convert_from(
background_image,
)
}),
payment_button_text: item.payment_button_text,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
skip_status_screen: item.skip_status_screen,
background_colour: item.background_colour,
payment_button_text_colour: item.payment_button_text_colour,
sdk_ui_rules: item.sdk_ui_rules,
payment_link_ui_rules: item.payment_link_ui_rules,
enable_button_only_on_form_ready: item.enable_button_only_on_form_ready,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest {
let Self {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
transaction_details,
background_image,
details_layout,
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
} = self;
api_models::admin::PaymentLinkConfigRequest {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
details_layout,
transaction_details: transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| transaction_detail.convert_back())
.collect()
}),
background_image: background_image
.map(|background_image| background_image.convert_back()),
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDetails>
for diesel_models::PaymentLinkTransactionDetails
{
fn convert_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self {
Self {
key: from.key,
value: from.value,
ui_configuration: from
.ui_configuration
.map(diesel_models::TransactionDetailsUiConfiguration::convert_from),
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkTransactionDetails {
let Self {
key,
value,
ui_configuration,
} = self;
api_models::admin::PaymentLinkTransactionDetails {
key,
value,
ui_configuration: ui_configuration
.map(|ui_configuration| ui_configuration.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkBackgroundImageConfig>
for diesel_models::business_profile::PaymentLinkBackgroundImageConfig
{
fn convert_from(from: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self {
Self {
url: from.url,
position: from.position,
size: from.size,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkBackgroundImageConfig {
let Self {
url,
position,
size,
} = self;
api_models::admin::PaymentLinkBackgroundImageConfig {
url,
position,
size,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration>
for diesel_models::TransactionDetailsUiConfiguration
{
fn convert_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self {
Self {
position: from.position,
is_key_bold: from.is_key_bold,
is_value_bold: from.is_value_bold,
}
}
fn convert_back(self) -> api_models::admin::TransactionDetailsUiConfiguration {
let Self {
position,
is_key_bold,
is_value_bold,
} = self;
api_models::admin::TransactionDetailsUiConfiguration {
position,
is_key_bold,
is_value_bold,
}
}
}
#[cfg(feature = "v2")]
impl From<api_models::payments::AmountDetails> for payments::AmountDetails {
fn from(amount_details: api_models::payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount().into(),
currency: amount_details.currency(),
shipping_cost: amount_details.shipping_cost(),
tax_details: amount_details.order_tax_amount().map(|order_tax_amount| {
diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax { order_tax_amount }),
payment_method_type: None,
}
}),
skip_external_tax_calculation: amount_details.skip_external_tax_calculation(),
skip_surcharge_calculation: amount_details.skip_surcharge_calculation(),
surcharge_amount: amount_details.surcharge_amount(),
tax_on_surcharge: amount_details.tax_on_surcharge(),
// We will not receive this in the request. This will be populated after calling the connector / processor
amount_captured: None,
}
}
}
#[cfg(feature = "v2")]
impl From<payments::AmountDetails> for api_models::payments::AmountDetailsSetter {
fn from(amount_details: payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount.into(),
currency: amount_details.currency,
shipping_cost: amount_details.shipping_cost,
order_tax_amount: amount_details
.tax_details
.and_then(|tax_detail| tax_detail.get_default_tax_amount()),
skip_external_tax_calculation: amount_details.skip_external_tax_calculation,
skip_surcharge_calculation: amount_details.skip_surcharge_calculation,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
}
}
}
#[cfg(feature = "v2")]
impl From<&api_models::payments::PaymentAttemptAmountDetails>
for payments::payment_attempt::AttemptAmountDetailsSetter
{
fn from(amount: &api_models::payments::PaymentAttemptAmountDetails) -> Self {
Self {
net_amount: amount.net_amount,
amount_to_capture: amount.amount_to_capture,
surcharge_amount: amount.surcharge_amount,
tax_on_surcharge: amount.tax_on_surcharge,
amount_capturable: amount.amount_capturable,
shipping_cost: amount.shipping_cost,
order_tax_amount: amount.order_tax_amount,
}
}
}
#[cfg(feature = "v2")]
impl From<&api_models::payments::RecordAttemptErrorDetails>
for payments::payment_attempt::ErrorDetails
{
fn from(error: &api_models::payments::RecordAttemptErrorDetails) -> Self {
Self {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
unified_code: None,
unified_message: None,
network_advice_code: error.network_advice_code.clone(),
network_decline_code: error.network_decline_code.clone(),
network_error_message: error.network_error_message.clone(),
}
}
}
| 4,254 | 2,404 |
hyperswitch | crates/hyperswitch_domain_models/src/payouts.rs | .rs | pub mod payout_attempt;
#[allow(clippy::module_inception)]
pub mod payouts;
use common_enums as storage_enums;
use common_utils::{consts, id_type};
use time::PrimitiveDateTime;
pub enum PayoutFetchConstraints {
Single { payout_id: String },
List(Box<PayoutListParams>),
}
pub struct PayoutListParams {
pub offset: u32,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub connector: Option<Vec<api_models::enums::PayoutConnectors>>,
pub currency: Option<Vec<storage_enums::Currency>>,
pub status: Option<Vec<storage_enums::PayoutStatus>>,
pub payout_method: Option<Vec<common_enums::PayoutType>>,
pub profile_id: Option<id_type::ProfileId>,
pub customer_id: Option<id_type::CustomerId>,
pub starting_after_id: Option<String>,
pub ending_before_id: Option<String>,
pub entity_type: Option<common_enums::PayoutEntityType>,
pub limit: Option<u32>,
}
impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints {
fn from(value: api_models::payouts::PayoutListConstraints) -> Self {
Self::List(Box::new(PayoutListParams {
offset: 0,
starting_at: value
.time_range
.map_or(value.created, |t| Some(t.start_time)),
ending_at: value.time_range.and_then(|t| t.end_time),
connector: None,
currency: None,
status: None,
payout_method: None,
profile_id: None,
customer_id: value.customer_id,
starting_after_id: value.starting_after,
ending_before_id: value.ending_before,
entity_type: None,
limit: Some(std::cmp::min(
value.limit,
consts::PAYOUTS_LIST_MAX_LIMIT_GET,
)),
}))
}
}
impl From<common_utils::types::TimeRange> for PayoutFetchConstraints {
fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PayoutListParams {
offset: 0,
starting_at: Some(value.start_time),
ending_at: value.end_time,
connector: None,
currency: None,
status: None,
payout_method: None,
profile_id: None,
customer_id: None,
starting_after_id: None,
ending_before_id: None,
entity_type: None,
limit: None,
}))
}
}
impl From<api_models::payouts::PayoutListFilterConstraints> for PayoutFetchConstraints {
fn from(value: api_models::payouts::PayoutListFilterConstraints) -> Self {
if let Some(payout_id) = value.payout_id {
Self::Single { payout_id }
} else {
Self::List(Box::new(PayoutListParams {
offset: value.offset.unwrap_or_default(),
starting_at: value.time_range.map(|t| t.start_time),
ending_at: value.time_range.and_then(|t| t.end_time),
connector: value.connector,
currency: value.currency,
status: value.status,
payout_method: value.payout_method,
profile_id: value.profile_id,
customer_id: value.customer_id,
starting_after_id: None,
ending_before_id: None,
entity_type: value.entity_type,
limit: Some(std::cmp::min(
value.limit,
consts::PAYOUTS_LIST_MAX_LIMIT_POST,
)),
}))
}
}
}
| 776 | 2,405 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.