id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
file_analytics_-2937683820280606560 | clm | file | // Repository: hyperswitch
// Crate: analytics
// File: crates/analytics/src/refunds/core.rs
// Contains: 0 structs, 1 enums
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use api_models::analytics::{
refunds::{
RefundDimensions, RefundDistributions, RefundMetrics, RefundMetricsBucketIdentifier,
RefundMetricsBucketResponse,
},
GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse,
RefundsAnalyticsMetadata, RefundsMetricsResponse,
};
use bigdecimal::ToPrimitive;
use common_enums::Currency;
use common_utils::errors::CustomResult;
use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
logger,
tracing::{self, Instrument},
};
use super::{
distribution::RefundDistributionRow,
filters::{get_refund_filter_for_dimension, RefundFilterRow},
metrics::RefundMetricRow,
RefundMetricsAccumulator,
};
use crate::{
enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics,
refunds::{accumulator::RefundDistributionAccumulator, RefundMetricAccumulator},
AnalyticsProvider,
};
#[derive(Debug)]
pub enum TaskType {
MetricTask(
RefundMetrics,
CustomResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, AnalyticsError>,
),
DistributionTask(
RefundDistributions,
CustomResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, AnalyticsError>,
),
}
pub async fn get_metrics(
pool: &AnalyticsProvider,
ex_rates: &Option<ExchangeRates>,
auth: &AuthInfo,
req: GetRefundMetricRequest,
) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> =
HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_refund_query",
refund_metric = metric_type.as_ref()
);
// Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference
// We can optimize away this clone once that is fixed
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_refund_metrics(
&metric_type,
&req.group_by_names.clone(),
&auth_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
TaskType::MetricTask(metric_type, data)
}
.instrument(task_span),
);
}
if let Some(distribution) = req.clone().distribution {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_refunds_distribution_query",
refund_distribution = distribution.distribution_for.as_ref()
);
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_refund_distribution(
&distribution,
&req.group_by_names.clone(),
&auth_scoped,
&req.filters,
&req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
TaskType::DistributionTask(distribution.distribution_for, data)
}
.instrument(task_span),
);
}
while let Some(task_type) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
match task_type {
TaskType::MetricTask(metric, data) => {
let data = data?;
let attributes = router_env::metric_attributes!(
("metric_type", metric.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
RefundMetrics::RefundSuccessRate
| RefundMetrics::SessionizedRefundSuccessRate => metrics_builder
.refund_success_rate
.add_metrics_bucket(&value),
RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => {
metrics_builder.refund_count.add_metrics_bucket(&value)
}
RefundMetrics::RefundSuccessCount
| RefundMetrics::SessionizedRefundSuccessCount => {
metrics_builder.refund_success.add_metrics_bucket(&value)
}
RefundMetrics::RefundProcessedAmount
| RefundMetrics::SessionizedRefundProcessedAmount => {
metrics_builder.processed_amount.add_metrics_bucket(&value)
}
RefundMetrics::SessionizedRefundReason => {
metrics_builder.refund_reason.add_metrics_bucket(&value)
}
RefundMetrics::SessionizedRefundErrorMessage => metrics_builder
.refund_error_message
.add_metrics_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
TaskType::DistributionTask(distribution, data) => {
let data = data?;
let attributes = router_env::metric_attributes!(
("distribution_type", distribution.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match distribution {
RefundDistributions::SessionizedRefundReason => metrics_builder
.refund_reason_distribution
.add_distribution_bucket(&value),
RefundDistributions::SessionizedRefundErrorMessage => metrics_builder
.refund_error_message_distribution
.add_distribution_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: distribution: {}, results: {:#?}",
distribution,
metrics_accumulator
);
}
}
}
let mut success = 0;
let mut total = 0;
let mut total_refund_processed_amount = 0;
let mut total_refund_processed_amount_in_usd = 0;
let mut total_refund_processed_count = 0;
let mut total_refund_reason_count = 0;
let mut total_refund_error_message_count = 0;
let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
let mut collected_values = val.collect();
if let Some(success_count) = collected_values.successful_refunds {
success += success_count;
}
if let Some(total_count) = collected_values.total_refunds {
total += total_count;
}
if let Some(amount) = collected_values.refund_processed_amount {
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.refund_processed_amount_in_usd = amount_in_usd;
total_refund_processed_amount += amount;
total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.refund_processed_count {
total_refund_processed_count += count;
}
if let Some(total_count) = collected_values.refund_reason_count {
total_refund_reason_count += total_count;
}
if let Some(total_count) = collected_values.refund_error_message_count {
total_refund_error_message_count += total_count;
}
RefundMetricsBucketResponse {
values: collected_values,
dimensions: id,
}
})
.collect();
let total_refund_success_rate = match (success, total) {
(s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
Ok(RefundsMetricsResponse {
query_data,
meta_data: [RefundsAnalyticsMetadata {
total_refund_success_rate,
total_refund_processed_amount: Some(total_refund_processed_amount),
total_refund_processed_amount_in_usd: if ex_rates.is_some() {
Some(total_refund_processed_amount_in_usd)
} else {
None
},
total_refund_processed_count: Some(total_refund_processed_count),
total_refund_reason_count: Some(total_refund_reason_count),
total_refund_error_message_count: Some(total_refund_error_message_count),
}],
})
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetRefundFilterRequest,
auth: &AuthInfo,
) -> AnalyticsResult<RefundFiltersResponse> {
let mut res = RefundFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_refund_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_refund_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => {
let ckh_result = get_refund_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_refund_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => {
let ckh_result = get_refund_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_refund_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: RefundFilterRow| match dim {
RefundDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
RefundDimensions::RefundStatus => fil.refund_status.map(|i| i.as_ref().to_string()),
RefundDimensions::Connector => fil.connector,
RefundDimensions::RefundType => fil.refund_type.map(|i| i.as_ref().to_string()),
RefundDimensions::ProfileId => fil.profile_id,
RefundDimensions::RefundReason => fil.refund_reason,
RefundDimensions::RefundErrorMessage => fil.refund_error_message,
})
.collect::<Vec<String>>();
res.query_data.push(RefundFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
| {
"crate": "analytics",
"file": "crates/analytics/src/refunds/core.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_578915850663119059 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/secrets_interface.rs
// Contains: 0 structs, 1 enums
//! Secrets management interface
pub mod secret_handler;
pub mod secret_state;
use common_utils::errors::CustomResult;
use masking::Secret;
/// Trait defining the interface for managing application secrets
#[async_trait::async_trait]
pub trait SecretManagementInterface: Send + Sync {
/*
/// Given an input, encrypt/store the secret
async fn store_secret(
&self,
input: Secret<String>,
) -> CustomResult<String, SecretsManagementError>;
*/
/// Given an input, decrypt/retrieve the secret
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError>;
}
/// Errors that may occur during secret management
#[derive(Debug, thiserror::Error)]
pub enum SecretsManagementError {
/// An error occurred when retrieving raw data.
#[error("Failed to fetch the raw data")]
FetchSecretFailed,
/// Failed while creating kms client
#[error("Failed while creating a secrets management client")]
ClientCreationFailed,
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/secrets_interface.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_-5338718119518771107 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/connector_integration_interface.rs
// Contains: 0 structs, 2 enums
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::PaymentAction;
use common_utils::{crypto, errors::CustomResult, request::Request};
use hyperswitch_domain_models::{
api::ApplicationResponse,
connector_endpoints::Connectors,
errors::api_error_response::ApiErrorResponse,
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::RouterDataV2,
router_response_types::{ConnectorInfo, SupportedPaymentMethods},
};
use crate::{
api,
api::{
BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorCommon,
ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation, CurrencyUnit,
},
authentication::ExternalAuthenticationPayload,
connector_integration_v2::{BoxedConnectorIntegrationV2, ConnectorIntegrationV2, ConnectorV2},
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types,
webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails},
};
/// RouterDataConversion trait
///
/// This trait must be implemented for conversion between Router data and RouterDataV2
pub trait RouterDataConversion<T, Req: Clone, Resp: Clone> {
/// Convert RouterData to RouterDataV2
///
/// # Arguments
///
/// * `old_router_data` - A reference to the old RouterData
///
/// # Returns
///
/// A `CustomResult` containing the new RouterDataV2 or a ConnectorError
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, errors::ConnectorError>
where
Self: Sized;
/// Convert RouterDataV2 back to RouterData
///
/// # Arguments
///
/// * `new_router_data` - The new RouterDataV2
///
/// # Returns
///
/// A `CustomResult` containing the old RouterData or a ConnectorError
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
Self: Sized;
}
/// Alias for Box<&'static (dyn Connector + Sync)>
pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
/// Alias for Box<&'static (dyn ConnectorV2 + Sync)>
pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>;
/// Enum representing the Connector
#[derive(Clone)]
pub enum ConnectorEnum {
/// Old connector type
Old(BoxedConnector),
/// New connector type
New(BoxedConnectorV2),
}
impl std::fmt::Debug for ConnectorEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Old(_) => f
.debug_tuple("Old")
.field(&std::any::type_name::<BoxedConnector>().to_string())
.finish(),
Self::New(_) => f
.debug_tuple("New")
.field(&std::any::type_name::<BoxedConnectorV2>().to_string())
.finish(),
}
}
}
#[allow(missing_debug_implementations)]
/// Enum representing the Connector Integration
#[derive(Clone)]
pub enum ConnectorIntegrationEnum<'a, F, ResourceCommonData, Req, Resp> {
/// Old connector integration type
Old(BoxedConnectorIntegration<'a, F, Req, Resp>),
/// New connector integration type
New(BoxedConnectorIntegrationV2<'a, F, ResourceCommonData, Req, Resp>),
}
/// Alias for Box<dyn ConnectorIntegrationInterface>
pub type BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> =
Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>;
impl ConnectorEnum {
/// Get the connector integration
///
/// # Returns
///
/// A `BoxedConnectorIntegrationInterface` containing the connector integration
pub fn get_connector_integration<F, ResourceCommonData, Req, Resp>(
&self,
) -> BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>
where
dyn Connector + Sync: ConnectorIntegration<F, Req, Resp>,
dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, ResourceCommonData, Req, Resp>,
ResourceCommonData: RouterDataConversion<F, Req, Resp> + Clone + 'static,
F: Clone + 'static,
Req: Clone + 'static,
Resp: Clone + 'static,
{
match self {
Self::Old(old_integration) => Box::new(ConnectorIntegrationEnum::Old(
old_integration.get_connector_integration(),
)),
Self::New(new_integration) => Box::new(ConnectorIntegrationEnum::New(
new_integration.get_connector_integration_v2(),
)),
}
}
/// validates the file upload
pub fn validate_file_upload(
&self,
purpose: api::files::FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_file_upload(purpose, file_size, file_type),
Self::New(connector) => {
connector.validate_file_upload_v2(purpose, file_size, file_type)
}
}
}
}
#[async_trait::async_trait]
impl IncomingWebhook for ConnectorEnum {
fn get_webhook_body_decoding_algorithm(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_body_decoding_algorithm(request),
Self::New(connector) => connector.get_webhook_body_decoding_algorithm(request),
}
}
fn get_webhook_body_decoding_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_body_decoding_message(request),
Self::New(connector) => connector.get_webhook_body_decoding_message(request),
}
}
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => {
connector
.decode_webhook_body(
request,
merchant_id,
connector_webhook_details,
connector_name,
)
.await
}
Self::New(connector) => {
connector
.decode_webhook_body(
request,
merchant_id,
connector_webhook_details,
connector_name,
)
.await
}
}
}
fn get_webhook_source_verification_algorithm(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_source_verification_algorithm(request),
Self::New(connector) => connector.get_webhook_source_verification_algorithm(request),
}
}
async fn get_webhook_source_verification_merchant_secret(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> {
match self {
Self::Old(connector) => {
connector
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
}
Self::New(connector) => {
connector
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
}
}
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector
.get_webhook_source_verification_signature(request, connector_webhook_secrets),
Self::New(connector) => connector
.get_webhook_source_verification_signature(request, connector_webhook_secrets),
}
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_source_verification_message(
request,
merchant_id,
connector_webhook_secrets,
),
Self::New(connector) => connector.get_webhook_source_verification_message(
request,
merchant_id,
connector_webhook_secrets,
),
}
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
match self {
Self::Old(connector) => {
connector
.verify_webhook_source(
request,
merchant_id,
connector_webhook_details,
connector_account_details,
connector_name,
)
.await
}
Self::New(connector) => {
connector
.verify_webhook_source(
request,
merchant_id,
connector_webhook_details,
connector_account_details,
connector_name,
)
.await
}
}
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_object_reference_id(request),
Self::New(connector) => connector.get_webhook_object_reference_id(request),
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_event_type(request),
Self::New(connector) => connector.get_webhook_event_type(request),
}
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_resource_object(request),
Self::New(connector) => connector.get_webhook_resource_object(request),
}
}
fn get_webhook_api_response(
&self,
request: &IncomingWebhookRequestDetails<'_>,
error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_api_response(request, error_kind),
Self::New(connector) => connector.get_webhook_api_response(request, error_kind),
}
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_dispute_details(request),
Self::New(connector) => connector.get_dispute_details(request),
}
}
fn get_external_authentication_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_external_authentication_details(request),
Self::New(connector) => connector.get_external_authentication_details(request),
}
}
fn get_mandate_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_mandate_details(request),
Self::New(connector) => connector.get_mandate_details(request),
}
}
fn get_network_txn_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_network_txn_id(request),
Self::New(connector) => connector.get_network_txn_id(request),
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_invoice_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_revenue_recovery_invoice_details(request),
Self::New(connector) => connector.get_revenue_recovery_invoice_details(request),
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_attempt_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_revenue_recovery_attempt_details(request),
Self::New(connector) => connector.get_revenue_recovery_attempt_details(request),
}
}
fn get_subscription_mit_payment_data(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_subscription_mit_payment_data(request),
Self::New(connector) => connector.get_subscription_mit_payment_data(request),
}
}
}
impl ConnectorRedirectResponse for ConnectorEnum {
fn get_flow_type(
&self,
query_params: &str,
json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<common_enums::CallConnectorAction, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_flow_type(query_params, json_payload, action),
Self::New(connector) => connector.get_flow_type(query_params, json_payload, action),
}
}
}
impl ConnectorValidation for ConnectorEnum {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<common_enums::CaptureMethod>,
payment_method: common_enums::PaymentMethod,
pmt: Option<common_enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_connector_against_payment_request(
capture_method,
payment_method,
pmt,
),
Self::New(connector) => connector.validate_connector_against_payment_request(
capture_method,
payment_method,
pmt,
),
}
}
fn validate_mandate_payment(
&self,
pm_type: Option<common_enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_mandate_payment(pm_type, pm_data),
Self::New(connector) => connector.validate_mandate_payment(pm_type, pm_data),
}
}
fn validate_psync_reference_id(
&self,
data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
is_three_ds: bool,
status: common_enums::enums::AttemptStatus,
connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_psync_reference_id(
data,
is_three_ds,
status,
connector_meta_data,
),
Self::New(connector) => connector.validate_psync_reference_id(
data,
is_three_ds,
status,
connector_meta_data,
),
}
}
fn is_webhook_source_verification_mandatory(&self) -> bool {
match self {
Self::Old(connector) => connector.is_webhook_source_verification_mandatory(),
Self::New(connector) => connector.is_webhook_source_verification_mandatory(),
}
}
}
impl ConnectorSpecifications for ConnectorEnum {
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
match self {
Self::Old(connector) => connector.get_supported_payment_methods(),
Self::New(connector) => connector.get_supported_payment_methods(),
}
}
/// Supported webhooks flows
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
match self {
Self::Old(connector) => connector.get_supported_webhook_flows(),
Self::New(connector) => connector.get_supported_webhook_flows(),
}
}
/// Details related to connector
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
match self {
Self::Old(connector) => connector.get_connector_about(),
Self::New(connector) => connector.get_connector_about(),
}
}
/// Check if connector supports authentication token
fn authentication_token_for_token_creation(&self) -> bool {
match self {
Self::Old(connector) => connector.authentication_token_for_token_creation(),
Self::New(connector) => connector.authentication_token_for_token_creation(),
}
}
/// If connector supports session token generation
fn is_sdk_client_token_generation_enabled(&self) -> bool {
match self {
Self::Old(connector) => connector.is_sdk_client_token_generation_enabled(),
Self::New(connector) => connector.is_sdk_client_token_generation_enabled(),
}
}
/// Supported payment methods for session token generation
fn supported_payment_method_types_for_sdk_client_token_generation(
&self,
) -> Vec<common_enums::PaymentMethodType> {
match self {
Self::Old(connector) => {
connector.supported_payment_method_types_for_sdk_client_token_generation()
}
Self::New(connector) => {
connector.supported_payment_method_types_for_sdk_client_token_generation()
}
}
}
/// Validate whether session token is generated for payment payment type
fn validate_sdk_session_token_for_payment_method(
&self,
current_core_payment_method_type: &common_enums::PaymentMethodType,
) -> bool {
match self {
Self::Old(connector) => connector
.validate_sdk_session_token_for_payment_method(current_core_payment_method_type),
Self::New(connector) => connector
.validate_sdk_session_token_for_payment_method(current_core_payment_method_type),
}
}
#[cfg(feature = "v1")]
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
is_config_enabled_to_send_payment_id_as_connector_request_id: bool,
) -> String {
match self {
Self::Old(connector) => connector.generate_connector_request_reference_id(
payment_intent,
payment_attempt,
is_config_enabled_to_send_payment_id_as_connector_request_id,
),
Self::New(connector) => connector.generate_connector_request_reference_id(
payment_intent,
payment_attempt,
is_config_enabled_to_send_payment_id_as_connector_request_id,
),
}
}
#[cfg(feature = "v2")]
/// Generate connector request reference ID
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
match self {
Self::Old(connector) => {
connector.generate_connector_request_reference_id(payment_intent, payment_attempt)
}
Self::New(connector) => {
connector.generate_connector_request_reference_id(payment_intent, payment_attempt)
}
}
}
/// Check if connector requires create customer call
fn should_call_connector_customer(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
match self {
Self::Old(connector) => connector.should_call_connector_customer(payment_attempt),
Self::New(connector) => connector.should_call_connector_customer(payment_attempt),
}
}
}
impl ConnectorCommon for ConnectorEnum {
fn id(&self) -> &'static str {
match self {
Self::Old(connector) => connector.id(),
Self::New(connector) => connector.id(),
}
}
fn get_currency_unit(&self) -> CurrencyUnit {
match self {
Self::Old(connector) => connector.get_currency_unit(),
Self::New(connector) => connector.get_currency_unit(),
}
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_auth_header(auth_type),
Self::New(connector) => connector.get_auth_header(auth_type),
}
}
fn common_get_content_type(&self) -> &'static str {
match self {
Self::Old(connector) => connector.common_get_content_type(),
Self::New(connector) => connector.common_get_content_type(),
}
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
match self {
Self::Old(connector) => connector.base_url(connectors),
Self::New(connector) => connector.base_url(connectors),
}
}
fn build_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.build_error_response(res, event_builder),
Self::New(connector) => connector.build_error_response(res, event_builder),
}
}
}
/// Trait representing the connector integration interface
///
/// This trait defines the methods required for a connector integration interface.
pub trait ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>: Send + Sync {
/// Clone the connector integration interface
///
/// # Returns
///
/// A `Box` containing the cloned connector integration interface
fn clone_box(
&self,
) -> Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>;
/// Get the multiple capture sync method
///
/// # Returns
///
/// A `CustomResult` containing the `CaptureSyncMethod` or a `ConnectorError`
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError>;
/// Build a request for the connector integration
///
/// # Arguments
///
/// * `req` - A reference to the RouterData
/// # Returns
///
/// A `CustomResult` containing an optional Request or a ConnectorError
fn build_request(
&self,
req: &RouterData<F, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError>;
/// handles response from the connector
fn handle_response(
&self,
data: &RouterData<F, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<RouterData<F, Req, Resp>, errors::ConnectorError>
where
F: Clone,
Req: Clone,
Resp: Clone;
/// Get the error response
///
/// # Arguments
///
/// * `res` - The response
/// * `event_builder` - An optional event builder
///
/// # Returns
///
/// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError`
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError>;
/// Get the 5xx error response
///
/// # Arguments
///
/// * `res` - The response
/// * `event_builder` - An optional event builder
///
/// # Returns
///
/// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError`
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError>;
}
impl<T: 'static, ResourceCommonData: 'static, Req: 'static, Resp: 'static>
ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>
for ConnectorIntegrationEnum<'static, T, ResourceCommonData, Req, Resp>
where
ResourceCommonData: RouterDataConversion<T, Req, Resp> + Clone,
T: Clone,
Req: Clone,
Resp: Clone,
{
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.get_multiple_capture_sync_method()
}
ConnectorIntegrationEnum::New(new_integration) => {
new_integration.get_multiple_capture_sync_method()
}
}
}
fn build_request(
&self,
req: &RouterData<T, Req, Resp>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.build_request(req, connectors)
}
ConnectorIntegrationEnum::New(new_integration) => {
let new_router_data = ResourceCommonData::from_old_router_data(req)?;
new_integration.build_request_v2(&new_router_data)
}
}
}
fn handle_response(
&self,
data: &RouterData<T, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.handle_response(data, event_builder, res)
}
ConnectorIntegrationEnum::New(new_integration) => {
let new_router_data = ResourceCommonData::from_old_router_data(data)?;
new_integration
.handle_response_v2(&new_router_data, event_builder, res)
.map(ResourceCommonData::to_old_router_data)?
}
}
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.get_error_response(res, event_builder)
}
ConnectorIntegrationEnum::New(new_integration) => {
new_integration.get_error_response_v2(res, event_builder)
}
}
}
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.get_5xx_error_response(res, event_builder)
}
ConnectorIntegrationEnum::New(new_integration) => {
new_integration.get_5xx_error_response(res, event_builder)
}
}
}
fn clone_box(
&self,
) -> Box<dyn ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp> + Send + Sync>
{
Box::new(self.clone())
}
}
impl api::ConnectorTransactionId for ConnectorEnum {
/// Get the connector transaction ID
///
/// # Arguments
///
/// * `payment_attempt` - The payment attempt
///
/// # Returns
///
/// A `Result` containing an optional transaction ID or an ApiErrorResponse
fn connector_transaction_id(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
match self {
Self::Old(connector) => connector.connector_transaction_id(payment_attempt),
Self::New(connector) => connector.connector_transaction_id(payment_attempt),
}
}
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/connector_integration_interface.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_-8711482644167393174 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/encryption_interface.rs
// Contains: 0 structs, 1 enums
//! Encryption related interface and error types
#![warn(missing_docs, missing_debug_implementations)]
use common_utils::errors::CustomResult;
/// Trait defining the interface for encryption management
#[async_trait::async_trait]
pub trait EncryptionManagementInterface: Sync + Send + dyn_clone::DynClone {
/// Encrypt the given input data
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>;
/// Decrypt the given input data
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>;
}
dyn_clone::clone_trait_object!(EncryptionManagementInterface);
/// Errors that may occur during above encryption functionalities
#[derive(Debug, thiserror::Error)]
pub enum EncryptionError {
/// An error occurred when encrypting input data.
#[error("Failed to encrypt input data")]
EncryptionFailed,
/// An error occurred when decrypting input data.
#[error("Failed to decrypt input data")]
DecryptionFailed,
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/encryption_interface.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_-2098936818955319925 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/errors.rs
// Contains: 0 structs, 2 enums
//! Errors interface
use common_enums::ApiClientError;
use common_utils::errors::ErrorSwitch;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
/// Connector Errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Connector wallet details not found")]
NoConnectorWalletDetails,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector mandate ID")]
MissingConnectorMandateID,
#[error("Missing connector mandate metadata")]
MissingConnectorMandateMetadata,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Missing apple pay tokenization data")]
MissingApplePayTokenData,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Merchant secret found for incoming webhook source verification is invalid")]
WebhookVerificationSecretInvalid,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Failed to parse {wallet_name} wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
#[error("Failed at connector's end with code '{code}'")]
FailedAtConnector { message: String, code: String },
#[error("Payment Method Type not found")]
MissingPaymentMethodType,
#[error("Balance in the payment method is low")]
InSufficientBalanceInPaymentMethod,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("The given currency method is not configured with the given connector")]
CurrencyNotSupported {
message: String,
connector: &'static str,
},
#[error("Invalid Configuration")]
InvalidConnectorConfig { config: &'static str },
#[error("Failed to convert amount to required type")]
AmountConversionFailed,
#[error("Generic Error")]
GenericError {
error_message: String,
error_object: serde_json::Value,
},
#[error("Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
#[error("Field '{field_name}' is too long for connector '{connector}'")]
MaxFieldLengthViolated {
connector: String,
field_name: String,
max_length: usize,
received_length: usize,
},
}
impl ConnectorError {
/// fn is_connector_timeout
pub fn is_connector_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
}
impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError {
fn switch(&self) -> ConnectorError {
ConnectorError::ParsingFailed
}
}
impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
Self::WebhookSignatureNotFound
| Self::WebhookReferenceIdNotFound
| Self::WebhookResourceObjectNotFound
| Self::WebhookBodyDecodingFailed
| Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
Self::WebhookVerificationSecretInvalid => {
ApiErrorResponse::WebhookInvalidMerchantSecret
}
_ => ApiErrorResponse::InternalServerError,
}
}
}
// http client errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
pub enum HttpClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
#[error("Invalid proxy configuration")]
InvalidProxyConfiguration,
#[error("Client construction failed")]
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
#[error("Request body serialization failed")]
BodySerializationFailed,
#[error("Unexpected state reached/Invariants conflicted")]
UnexpectedState,
#[error("Failed to parse URL")]
UrlParsingFailed,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
#[error("Failed to send request to connector {0}")]
RequestNotSent(String),
#[error("Failed to decode response")]
ResponseDecodingFailed,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("connection closed before a message could complete")]
ConnectionClosedIncompleteMessage,
#[error("Server responded with Internal Server Error")]
InternalServerErrorReceived,
#[error("Server responded with Bad Gateway")]
BadGatewayReceived,
#[error("Server responded with Service Unavailable")]
ServiceUnavailableReceived,
#[error("Server responded with Gateway Timeout")]
GatewayTimeoutReceived,
#[error("Server responded with unexpected response")]
UnexpectedServerResponse,
}
impl ErrorSwitch<ApiClientError> for HttpClientError {
fn switch(&self) -> ApiClientError {
match self {
Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed,
Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration,
Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed,
Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed,
Self::BodySerializationFailed => ApiClientError::BodySerializationFailed,
Self::UnexpectedState => ApiClientError::UnexpectedState,
Self::UrlParsingFailed => ApiClientError::UrlParsingFailed,
Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed,
Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()),
Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed,
Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived,
Self::ConnectionClosedIncompleteMessage => {
ApiClientError::ConnectionClosedIncompleteMessage
}
Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived,
Self::BadGatewayReceived => ApiClientError::BadGatewayReceived,
Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived,
Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived,
Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse,
}
}
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_-2644142419715152054 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/api.rs
// Contains: 0 structs, 2 enums
//! API interface
/// authentication module
pub mod authentication;
/// authentication_v2 module
pub mod authentication_v2;
pub mod disputes;
pub mod disputes_v2;
pub mod files;
pub mod files_v2;
#[cfg(feature = "frm")]
pub mod fraud_check;
#[cfg(feature = "frm")]
pub mod fraud_check_v2;
pub mod payments;
pub mod payments_v2;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(feature = "payouts")]
pub mod payouts_v2;
pub mod refunds;
pub mod refunds_v2;
pub mod revenue_recovery;
pub mod revenue_recovery_v2;
pub mod subscriptions;
pub mod subscriptions_v2;
pub mod vault;
pub mod vault_v2;
use std::fmt::Debug;
use common_enums::{
enums::{CallConnectorAction, CaptureMethod, EventClass, PaymentAction, PaymentMethodType},
PaymentMethod,
};
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestContent},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
connector_endpoints::Connectors,
errors::api_error_response::ApiErrorResponse,
payment_method_data::PaymentMethodData,
router_data::{
AccessToken, AccessTokenAuthenticationResponse, ConnectorAuthType, ErrorResponse,
RouterData,
},
router_data_v2::{
flow_common_types::{AuthenticationTokenFlowData, WebhookSourceVerifyData},
AccessTokenFlowData, MandateRevokeFlowData, UasFlowData,
},
router_flow_types::{
mandate_revoke::MandateRevoke, AccessTokenAuth, AccessTokenAuthentication, Authenticate,
AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, VerifyWebhookSource,
},
router_request_types::{
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AccessTokenAuthenticationRequestData, AccessTokenRequestData, MandateRevokeRequestData,
VerifyWebhookSourceRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods,
VerifyWebhookSourceResponseData,
},
};
use masking::Maskable;
use serde_json::json;
#[cfg(feature = "frm")]
pub use self::fraud_check::*;
#[cfg(feature = "frm")]
pub use self::fraud_check_v2::*;
#[cfg(feature = "payouts")]
pub use self::payouts::*;
#[cfg(feature = "payouts")]
pub use self::payouts_v2::*;
pub use self::{payments::*, refunds::*, vault::*, vault_v2::*};
use crate::{
api::subscriptions::Subscriptions, connector_integration_v2::ConnectorIntegrationV2, consts,
errors, events::connector_api_logs::ConnectorEvent, metrics, types, webhooks,
};
/// Connector trait
pub trait Connector:
Send
+ Refund
+ Payment
+ ConnectorRedirectResponse
+ webhooks::IncomingWebhook
+ ConnectorAccessToken
+ ConnectorAuthenticationToken
+ disputes::Dispute
+ files::FileUpload
+ ConnectorTransactionId
+ Payouts
+ ConnectorVerifyWebhookSource
+ FraudCheck
+ ConnectorMandateRevoke
+ authentication::ExternalAuthentication
+ TaxCalculation
+ UnifiedAuthenticationService
+ revenue_recovery::RevenueRecovery
+ ExternalVault
+ Subscriptions
{
}
impl<
T: Refund
+ Payment
+ ConnectorRedirectResponse
+ Send
+ webhooks::IncomingWebhook
+ ConnectorAccessToken
+ ConnectorAuthenticationToken
+ disputes::Dispute
+ files::FileUpload
+ ConnectorTransactionId
+ Payouts
+ ConnectorVerifyWebhookSource
+ FraudCheck
+ ConnectorMandateRevoke
+ authentication::ExternalAuthentication
+ TaxCalculation
+ UnifiedAuthenticationService
+ revenue_recovery::RevenueRecovery
+ ExternalVault
+ Subscriptions,
> Connector for T
{
}
/// Alias for Box<&'static (dyn Connector + Sync)>
pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
/// type BoxedConnectorIntegration
pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
/// trait ConnectorIntegrationAny
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
/// fn get_connector_integration
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
}
impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
where
S: ConnectorIntegration<T, Req, Resp> + Send + Sync,
{
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
Box::new(self)
}
}
/// trait ConnectorIntegration
pub trait ConnectorIntegration<T, Req, Resp>:
ConnectorIntegrationAny<T, Req, Resp> + Sync + ConnectorCommon
{
/// fn get_headers
fn get_headers(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
/// fn get_content_type
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// fn get_content_type
fn get_accept_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// primarily used when creating signature based on request method of payment flow
fn get_http_method(&self) -> Method {
Method::Post
}
/// fn get_url
fn get_url(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(String::new())
}
/// fn get_request_body
fn get_request_body(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::Json(Box::new(json!(r#"{}"#))))
}
/// fn get_request_form_data
fn get_request_form_data(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
Ok(None)
}
/// fn build_request
fn build_request(
&self,
req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
metrics::UNIMPLEMENTED_FLOW.add(
1,
router_env::metric_attributes!(("connector", req.connector.clone())),
);
Ok(None)
}
/// fn handle_response
fn handle_response(
&self,
data: &RouterData<T, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
Ok(data.clone())
}
/// fn get_error_response
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
Ok(ErrorResponse::get_not_implemented())
}
/// fn get_5xx_error_response
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
Ok(ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
/// whenever capture sync is implemented at the connector side, this method should be overridden
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
}
/// fn get_certificate
fn get_certificate(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
Ok(None)
}
/// fn get_certificate_key
fn get_certificate_key(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
Ok(None)
}
}
/// Sync Methods for multiple captures
#[derive(Debug)]
pub enum CaptureSyncMethod {
/// For syncing multiple captures individually
Individual,
/// For syncing multiple captures together
Bulk,
}
/// Connector accepted currency unit as either "Base" or "Minor"
#[derive(Debug)]
pub enum CurrencyUnit {
/// Base currency unit
Base,
/// Minor currency unit
Minor,
}
/// The trait that provides the common
pub trait ConnectorCommon {
/// Name of the connector (in lowercase).
fn id(&self) -> &'static str;
/// Connector accepted currency unit as either "Base" or "Minor"
fn get_currency_unit(&self) -> CurrencyUnit {
CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors
}
/// HTTP header used for authorization.
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(Vec::new())
}
/// HTTP `Content-Type` to be used for POST requests.
/// Defaults to `application/json`.
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
// FIXME write doc - think about this
// fn headers(&self) -> Vec<(&str, &str)>;
/// The base URL for interacting with the connector's API.
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str;
/// common error response for a connector if it is same in all case
fn build_error_response(
&self,
res: types::Response,
_event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
/// The trait that provides specifications about the connector
pub trait ConnectorSpecifications {
/// Details related to payment method supported by the connector
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
/// Supported webhooks flows
fn get_supported_webhook_flows(&self) -> Option<&'static [EventClass]> {
None
}
/// About the connector
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
None
}
/// Check if connector should make another request to create an access token
/// Connectors should override this method if they require an authentication token to create a new access token
fn authentication_token_for_token_creation(&self) -> bool {
false
}
/// Check if connector should make another request to create an customer
/// Connectors should override this method if they require to create a connector customer
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
false
}
/// Whether SDK session token generation is enabled for this connector
fn is_sdk_client_token_generation_enabled(&self) -> bool {
false
}
/// Payment method types that support SDK session token generation
fn supported_payment_method_types_for_sdk_client_token_generation(
&self,
) -> Vec<PaymentMethodType> {
vec![]
}
/// Validate if SDK session token generation is allowed for given payment method type
fn validate_sdk_session_token_for_payment_method(
&self,
current_core_payment_method_type: &PaymentMethodType,
) -> bool {
self.is_sdk_client_token_generation_enabled()
&& self
.supported_payment_method_types_for_sdk_client_token_generation()
.contains(current_core_payment_method_type)
}
#[cfg(not(feature = "v2"))]
/// Generate connector request reference ID
fn generate_connector_request_reference_id(
&self,
_payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
is_config_enabled_to_send_payment_id_as_connector_request_id: bool,
) -> String {
// Send payment_id if config is enabled for a merchant, else send attempt_id
if is_config_enabled_to_send_payment_id_as_connector_request_id {
payment_attempt.payment_id.get_string_repr().to_owned()
} else {
payment_attempt.attempt_id.to_owned()
}
}
#[cfg(feature = "v2")]
/// Generate connector request reference ID
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
payment_intent
.merchant_reference_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_else(|| payment_attempt.id.get_string_repr().to_owned())
}
}
/// Extended trait for connector common to allow functions with generic type
pub trait ConnectorCommonExt<Flow, Req, Resp>:
ConnectorCommon + ConnectorIntegration<Flow, Req, Resp>
{
/// common header builder when every request for the connector have same headers
fn build_headers(
&self,
_req: &RouterData<Flow, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(Vec::new())
}
}
/// trait ConnectorMandateRevoke
pub trait ConnectorMandateRevoke:
ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
{
}
/// trait ConnectorMandateRevokeV2
pub trait ConnectorMandateRevokeV2:
ConnectorIntegrationV2<
MandateRevoke,
MandateRevokeFlowData,
MandateRevokeRequestData,
MandateRevokeResponseData,
>
{
}
/// trait ConnectorAuthenticationToken
pub trait ConnectorAuthenticationToken:
ConnectorIntegration<
AccessTokenAuthentication,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
>
{
}
/// trait ConnectorAuthenticationTokenV2
pub trait ConnectorAuthenticationTokenV2:
ConnectorIntegrationV2<
AccessTokenAuthentication,
AuthenticationTokenFlowData,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
>
{
}
/// trait ConnectorAccessToken
pub trait ConnectorAccessToken:
ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
{
}
/// trait ConnectorAccessTokenV2
pub trait ConnectorAccessTokenV2:
ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken>
{
}
/// trait ConnectorVerifyWebhookSource
pub trait ConnectorVerifyWebhookSource:
ConnectorIntegration<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>
{
}
/// trait ConnectorVerifyWebhookSourceV2
pub trait ConnectorVerifyWebhookSourceV2:
ConnectorIntegrationV2<
VerifyWebhookSource,
WebhookSourceVerifyData,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>
{
}
/// trait UnifiedAuthenticationService
pub trait UnifiedAuthenticationService:
ConnectorCommon
+ UasPreAuthentication
+ UasPostAuthentication
+ UasAuthenticationConfirmation
+ UasAuthentication
{
}
/// trait UasPreAuthentication
pub trait UasPreAuthentication:
ConnectorIntegration<
PreAuthenticate,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasPostAuthentication
pub trait UasPostAuthentication:
ConnectorIntegration<
PostAuthenticate,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationConfirmation
pub trait UasAuthenticationConfirmation:
ConnectorIntegration<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthentication
pub trait UasAuthentication:
ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>
{
}
/// trait UnifiedAuthenticationServiceV2
pub trait UnifiedAuthenticationServiceV2:
ConnectorCommon
+ UasPreAuthenticationV2
+ UasPostAuthenticationV2
+ UasAuthenticationV2
+ UasAuthenticationConfirmationV2
{
}
///trait UasPreAuthenticationV2
pub trait UasPreAuthenticationV2:
ConnectorIntegrationV2<
PreAuthenticate,
UasFlowData,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasPostAuthenticationV2
pub trait UasPostAuthenticationV2:
ConnectorIntegrationV2<
PostAuthenticate,
UasFlowData,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationConfirmationV2
pub trait UasAuthenticationConfirmationV2:
ConnectorIntegrationV2<
AuthenticationConfirmation,
UasFlowData,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationV2
pub trait UasAuthenticationV2:
ConnectorIntegrationV2<
Authenticate,
UasFlowData,
UasAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait ConnectorValidation
pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications {
/// Validate, the payment request against the connector supported features
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
payment_method: PaymentMethod,
pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
let is_default_capture_method =
[CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic]
.contains(&capture_method);
let is_feature_supported = match self.get_supported_payment_methods() {
Some(supported_payment_methods) => {
let connector_payment_method_type_info = get_connector_payment_method_type_info(
supported_payment_methods,
payment_method,
pmt,
self.id(),
)?;
connector_payment_method_type_info
.map(|payment_method_type_info| {
payment_method_type_info
.supported_capture_methods
.contains(&capture_method)
})
.unwrap_or(true)
}
None => is_default_capture_method,
};
if is_feature_supported {
Ok(())
} else {
Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: self.id(),
}
.into())
}
}
/// fn validate_mandate_payment
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
_pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let connector = self.id();
match pm_type {
Some(pm_type) => Err(errors::ConnectorError::NotSupported {
message: format!("{pm_type} mandate payment"),
connector,
}
.into()),
None => Err(errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
/// fn validate_psync_reference_id
fn validate_psync_reference_id(
&self,
data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
data.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
.map(|_| ())
}
/// fn is_webhook_source_verification_mandatory
fn is_webhook_source_verification_mandatory(&self) -> bool {
false
}
}
/// trait ConnectorRedirectResponse
pub trait ConnectorRedirectResponse {
/// fn get_flow_type
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
_action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
Ok(CallConnectorAction::Avoid)
}
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait Payouts {}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait PayoutsV2 {}
/// Empty trait for when frm feature is disabled
#[cfg(not(feature = "frm"))]
pub trait FraudCheck {}
/// Empty trait for when frm feature is disabled
#[cfg(not(feature = "frm"))]
pub trait FraudCheckV2 {}
fn get_connector_payment_method_type_info(
supported_payment_method: &SupportedPaymentMethods,
payment_method: PaymentMethod,
payment_method_type: Option<PaymentMethodType>,
connector: &'static str,
) -> CustomResult<Option<PaymentMethodDetails>, errors::ConnectorError> {
let payment_method_details =
supported_payment_method
.get(&payment_method)
.ok_or_else(|| errors::ConnectorError::NotSupported {
message: payment_method.to_string(),
connector,
})?;
payment_method_type
.map(|pmt| {
payment_method_details.get(&pmt).cloned().ok_or_else(|| {
errors::ConnectorError::NotSupported {
message: format!("{payment_method} {pmt}"),
connector,
}
.into()
})
})
.transpose()
}
/// ConnectorTransactionId trait
pub trait ConnectorTransactionId: ConnectorCommon + Sync {
/// fn connector_transaction_id
fn connector_transaction_id(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
Ok(payment_attempt
.get_connector_payment_id()
.map(ToString::to_string))
}
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/api.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_4805050480318918437 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/api/files.rs
// Contains: 0 structs, 1 enums
//! Files interface
use hyperswitch_domain_models::{
router_flow_types::files::{Retrieve, Upload},
router_request_types::{RetrieveFileRequestData, UploadFileRequestData},
router_response_types::{RetrieveFileResponse, UploadFileResponse},
};
use crate::{
api::{ConnectorCommon, ConnectorIntegration},
errors,
};
/// enum FilePurpose
#[derive(Debug, serde::Deserialize, strum::Display, Clone, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FilePurpose {
/// DisputeEvidence
DisputeEvidence,
}
/// trait UploadFile
pub trait UploadFile:
ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>
{
}
/// trait RetrieveFile
pub trait RetrieveFile:
ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>
{
}
/// trait FileUpload
pub trait FileUpload: ConnectorCommon + Sync + UploadFile + RetrieveFile {
/// fn validate_file_upload
fn validate_file_upload(
&self,
_purpose: FilePurpose,
_file_size: i32,
_file_type: mime::Mime,
) -> common_utils::errors::CustomResult<(), errors::ConnectorError> {
Err(errors::ConnectorError::FileValidationFailed {
reason: "".to_owned(),
}
.into())
}
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/api/files.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_interfaces_-5822837583681509036 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_interfaces
// File: crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
// Contains: 0 structs, 2 enums
//! Routing API logs interface
use std::fmt;
use api_models::routing::RoutableConnectorChoice;
use common_utils::request::Method;
use router_env::tracing_actix_web::RequestId;
use serde::Serialize;
use serde_json::json;
use time::OffsetDateTime;
/// RoutingEngine enum
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingEngine {
/// Dynamo for routing
IntelligentRouter,
/// Decision engine for routing
DecisionEngine,
}
/// Method type enum
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ApiMethod {
/// grpc call
Grpc,
/// Rest call
Rest(Method),
}
impl fmt::Display for ApiMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Grpc => write!(f, "Grpc"),
Self::Rest(method) => write!(f, "Rest ({method})"),
}
}
}
#[derive(Debug, Serialize)]
/// RoutingEvent type
pub struct RoutingEvent {
tenant_id: common_utils::id_type::TenantId,
routable_connectors: String,
payment_connector: Option<String>,
flow: String,
request: String,
response: Option<String>,
error: Option<String>,
url: String,
method: String,
payment_id: String,
profile_id: common_utils::id_type::ProfileId,
merchant_id: common_utils::id_type::MerchantId,
created_at: i128,
status_code: Option<u16>,
request_id: String,
routing_engine: RoutingEngine,
routing_approach: Option<String>,
}
impl RoutingEvent {
/// fn new RoutingEvent
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
routable_connectors: String,
flow: &str,
request: serde_json::Value,
url: String,
method: ApiMethod,
payment_id: String,
profile_id: common_utils::id_type::ProfileId,
merchant_id: common_utils::id_type::MerchantId,
request_id: Option<RequestId>,
routing_engine: RoutingEngine,
) -> Self {
Self {
tenant_id,
routable_connectors,
flow: flow.to_string(),
request: request.to_string(),
response: None,
error: None,
url,
method: method.to_string(),
payment_id,
profile_id,
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),
status_code: None,
request_id: request_id
.map(|i| i.as_hyphenated().to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
routing_engine,
payment_connector: None,
routing_approach: None,
}
}
/// fn set_response_body
pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
match masking::masked_serialize(response) {
Ok(masked) => {
self.response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error_response_body
pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
match masking::masked_serialize(response) {
Ok(masked) => {
self.error = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error
pub fn set_error(&mut self, error: serde_json::Value) {
self.error = Some(error.to_string());
}
/// set response status code
pub fn set_status_code(&mut self, code: u16) {
self.status_code = Some(code);
}
/// set response status code
pub fn set_routable_connectors(&mut self, connectors: Vec<RoutableConnectorChoice>) {
let connectors = connectors
.into_iter()
.map(|c| {
format!(
"{:?}:{:?}",
c.connector,
c.merchant_connector_id
.map(|id| id.get_string_repr().to_string())
.unwrap_or(String::from(""))
)
})
.collect::<Vec<_>>()
.join(",");
self.routable_connectors = connectors;
}
/// set payment connector
pub fn set_payment_connector(&mut self, connector: RoutableConnectorChoice) {
self.payment_connector = Some(format!(
"{:?}:{:?}",
connector.connector,
connector
.merchant_connector_id
.map(|id| id.get_string_repr().to_string())
.unwrap_or(String::from(""))
));
}
/// set routing approach
pub fn set_routing_approach(&mut self, approach: String) {
self.routing_approach = Some(approach);
}
/// Returns the request ID of the event.
pub fn get_request_id(&self) -> &str {
&self.request_id
}
/// Returns the merchant ID of the event.
pub fn get_merchant_id(&self) -> &str {
self.merchant_id.get_string_repr()
}
/// Returns the payment ID of the event.
pub fn get_payment_id(&self) -> &str {
&self.payment_id
}
/// Returns the profile ID of the event.
pub fn get_profile_id(&self) -> &str {
self.profile_id.get_string_repr()
}
}
| {
"crate": "hyperswitch_interfaces",
"file": "crates/hyperswitch_interfaces/src/events/routing_api_logs.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_1714718681046704774 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/events.rs
// Contains: 0 structs, 3 enums
use std::collections::HashMap;
use common_utils::types::TenantConfig;
use error_stack::ResultExt;
use events::{EventsError, Message, MessagingInterface};
use hyperswitch_interfaces::events as events_interfaces;
use masking::ErasedMaskSerialize;
use router_env::logger;
use serde::{Deserialize, Serialize};
use storage_impl::errors::{ApplicationError, StorageError, StorageResult};
use time::PrimitiveDateTime;
use crate::{
db::KafkaProducer,
services::kafka::{KafkaMessage, KafkaSettings},
};
pub mod api_logs;
pub mod audit_events;
pub mod connector_api_logs;
pub mod event_logger;
pub mod outgoing_webhook_logs;
pub mod routing_api_logs;
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
PaymentIntent,
FraudCheck,
PaymentAttempt,
Refund,
ApiLogs,
ConnectorApiLogs,
OutgoingWebhookLogs,
Dispute,
AuditEvent,
#[cfg(feature = "payouts")]
Payout,
Consolidated,
Authentication,
RoutingApiLogs,
RevenueRecovery,
}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(tag = "source")]
#[serde(rename_all = "lowercase")]
pub enum EventsConfig {
Kafka {
kafka: Box<KafkaSettings>,
},
#[default]
Logs,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum EventsHandler {
Kafka(KafkaProducer),
Logs(event_logger::EventLogger),
}
impl Default for EventsHandler {
fn default() -> Self {
Self::Logs(event_logger::EventLogger {})
}
}
impl events_interfaces::EventHandlerInterface for EventsHandler {
fn log_connector_event(&self, event: &events_interfaces::connector_api_logs::ConnectorEvent) {
self.log_event(event);
}
}
impl EventsConfig {
pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> {
Ok(match self {
Self::Kafka { kafka } => EventsHandler::Kafka(
KafkaProducer::create(kafka)
.await
.change_context(StorageError::InitializationError)?,
),
Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()),
})
}
pub fn validate(&self) -> Result<(), ApplicationError> {
match self {
Self::Kafka { kafka } => kafka.validate(),
Self::Logs => Ok(()),
}
}
}
impl EventsHandler {
pub fn log_event<T: KafkaMessage>(&self, event: &T) {
match self {
Self::Kafka(kafka) => kafka.log_event(event).unwrap_or_else(|e| {
logger::error!("Failed to log event: {:?}", e);
}),
Self::Logs(logger) => logger.log_event(event),
};
}
pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) {
if let Self::Kafka(kafka_producer) = self {
kafka_producer.set_tenancy(tenant_config);
}
}
}
impl MessagingInterface for EventsHandler {
type MessageClass = EventType;
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize,
{
match self {
Self::Kafka(a) => a.send_message(data, metadata, timestamp),
Self::Logs(a) => a.send_message(data, metadata, timestamp),
}
}
}
| {
"crate": "router",
"file": "crates/router/src/events.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4214724542697324147 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/db.rs
// Contains: 0 structs, 1 enums
pub mod address;
pub mod api_keys;
pub mod authentication;
pub mod authorization;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod callback_mapper;
pub mod capture;
pub mod configs;
pub mod customers;
pub mod dashboard_metadata;
pub mod dispute;
pub mod dynamic_routing_stats;
pub mod ephemeral_key;
pub mod events;
pub mod file;
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod health_check;
pub mod hyperswitch_ai_interaction;
pub mod kafka_store;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod organization;
pub mod payment_link;
pub mod payment_method_session;
pub mod refund;
pub mod relay;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod unified_translations;
pub mod user;
pub mod user_authentication_method;
pub mod user_key_store;
pub mod user_role;
use ::payment_methods::state::PaymentMethodsStorageInterface;
use common_utils::id_type;
use diesel_models::{
fraud_check::{FraudCheck, FraudCheckUpdate},
organization::{Organization, OrganizationNew, OrganizationUpdate},
};
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
};
use hyperswitch_domain_models::{
cards_info::CardsInfoInterface,
master_key::MasterKeyInterface,
payment_methods::PaymentMethodInterface,
payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},
};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use redis_interface::errors::RedisError;
use router_env::logger;
use storage_impl::{
errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb,
};
pub use self::kafka_store::KafkaStore;
use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface};
pub use crate::{
core::errors::{self, ProcessTrackerError},
errors::CustomResult,
services::{
kafka::{KafkaError, KafkaProducer, MQResult},
Store,
},
types::{
domain,
storage::{self},
AccessToken,
},
};
#[derive(PartialEq, Eq)]
pub enum StorageImpl {
Postgresql,
PostgresqlTest,
Mock,
}
#[async_trait::async_trait]
pub trait StorageInterface:
Send
+ Sync
+ dyn_clone::DynClone
+ address::AddressInterface
+ api_keys::ApiKeyInterface
+ blocklist_lookup::BlocklistLookupInterface
+ configs::ConfigInterface<Error = StorageError>
+ capture::CaptureInterface
+ customers::CustomerInterface<Error = StorageError>
+ dashboard_metadata::DashboardMetadataInterface
+ dispute::DisputeInterface
+ ephemeral_key::EphemeralKeyInterface
+ ephemeral_key::ClientSecretInterface
+ events::EventInterface
+ file::FileMetadataInterface
+ FraudCheckInterface
+ locker_mock_up::LockerMockUpInterface
+ mandate::MandateInterface
+ merchant_account::MerchantAccountInterface<Error = StorageError>
+ merchant_connector_account::ConnectorAccessToken
+ merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>
+ PaymentAttemptInterface<Error = StorageError>
+ PaymentIntentInterface<Error = StorageError>
+ PaymentMethodInterface<Error = StorageError>
+ blocklist::BlocklistInterface
+ blocklist_fingerprint::BlocklistFingerprintInterface
+ dynamic_routing_stats::DynamicRoutingStatsInterface
+ scheduler::SchedulerInterface
+ PayoutAttemptInterface<Error = StorageError>
+ PayoutsInterface<Error = StorageError>
+ refund::RefundInterface
+ reverse_lookup::ReverseLookupInterface
+ CardsInfoInterface<Error = StorageError>
+ merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>
+ MasterKeyInterface
+ payment_link::PaymentLinkInterface
+ RedisConnInterface
+ RequestIdStore
+ business_profile::ProfileInterface<Error = StorageError>
+ routing_algorithm::RoutingAlgorithmInterface
+ gsm::GsmInterface
+ unified_translations::UnifiedTranslationsInterface
+ authorization::AuthorizationInterface
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ user_authentication_method::UserAuthenticationMethodInterface
+ hyperswitch_ai_interaction::HyperswitchAiInteractionInterface
+ authentication::AuthenticationInterface
+ generic_link::GenericLinkInterface
+ relay::RelayInterface
+ user::theme::ThemeInterface
+ payment_method_session::PaymentMethodsSessionInterface
+ tokenization::TokenizationInterface
+ callback_mapper::CallbackMapperInterface
+ storage_impl::subscription::SubscriptionInterface<Error = StorageError>
+ storage_impl::invoice::InvoiceInterface<Error = StorageError>
+ 'static
{
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;
fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>;
fn get_subscription_store(&self)
-> Box<dyn subscriptions::state::SubscriptionStorageInterface>;
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>;
}
#[async_trait::async_trait]
pub trait GlobalStorageInterface:
Send
+ Sync
+ dyn_clone::DynClone
+ user::UserInterface
+ user_role::UserRoleInterface
+ user_key_store::UserKeyStoreInterface
+ role::RoleInterface
+ RedisConnInterface
+ 'static
{
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>;
}
#[async_trait::async_trait]
pub trait AccountsStorageInterface:
Send
+ Sync
+ dyn_clone::DynClone
+ OrganizationInterface
+ merchant_account::MerchantAccountInterface<Error = StorageError>
+ business_profile::ProfileInterface<Error = StorageError>
+ merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>
+ merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>
+ dashboard_metadata::DashboardMetadataInterface
+ 'static
{
}
pub trait CommonStorageInterface:
StorageInterface
+ GlobalStorageInterface
+ AccountsStorageInterface
+ PaymentMethodsStorageInterface
{
fn get_storage_interface(&self) -> Box<dyn StorageInterface>;
fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface>;
fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface>;
}
#[async_trait::async_trait]
impl StorageInterface for Store {
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {
Box::new(self.clone())
}
fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {
Box::new(self.clone())
}
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
fn get_subscription_store(
&self,
) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> {
Box::new(self.clone())
}
}
#[async_trait::async_trait]
impl GlobalStorageInterface for Store {
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
}
impl AccountsStorageInterface for Store {}
#[async_trait::async_trait]
impl StorageInterface for MockDb {
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {
Box::new(self.clone())
}
fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {
Box::new(self.clone())
}
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
fn get_subscription_store(
&self,
) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> {
Box::new(self.clone())
}
}
#[async_trait::async_trait]
impl GlobalStorageInterface for MockDb {
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
}
impl AccountsStorageInterface for MockDb {}
impl CommonStorageInterface for MockDb {
fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> {
Box::new(self.clone())
}
fn get_storage_interface(&self) -> Box<dyn StorageInterface> {
Box::new(self.clone())
}
fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> {
Box::new(self.clone())
}
}
impl CommonStorageInterface for Store {
fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> {
Box::new(self.clone())
}
fn get_storage_interface(&self) -> Box<dyn StorageInterface> {
Box::new(self.clone())
}
fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> {
Box::new(self.clone())
}
}
pub trait RequestIdStore {
fn add_request_id(&mut self, _request_id: String) {}
fn get_request_id(&self) -> Option<String> {
None
}
}
impl RequestIdStore for MockDb {}
impl RequestIdStore for Store {
fn add_request_id(&mut self, request_id: String) {
self.request_id = Some(request_id)
}
fn get_request_id(&self) -> Option<String> {
self.request_id.clone()
}
}
pub async fn get_and_deserialize_key<T>(
db: &dyn StorageInterface,
key: &str,
type_name: &'static str,
) -> CustomResult<T, RedisError>
where
T: serde::de::DeserializeOwned,
{
use common_utils::ext_traits::ByteSliceExt;
let bytes = db.get_key(key).await?;
bytes
.parse_struct(type_name)
.change_context(RedisError::JsonDeserializationFailed)
}
dyn_clone::clone_trait_object!(StorageInterface);
dyn_clone::clone_trait_object!(GlobalStorageInterface);
dyn_clone::clone_trait_object!(AccountsStorageInterface);
impl RequestIdStore for KafkaStore {
fn add_request_id(&mut self, request_id: String) {
self.diesel_store.add_request_id(request_id)
}
}
#[async_trait::async_trait]
impl FraudCheckInterface for KafkaStore {
async fn insert_fraud_check_response(
&self,
new: storage::FraudCheckNew,
) -> CustomResult<FraudCheck, StorageError> {
let frm = self.diesel_store.insert_fraud_check_response(new).await?;
if let Err(er) = self
.kafka_producer
.log_fraud_check(&frm, None, self.tenant_id.clone())
.await
{
logger::error!(message = "Failed to log analytics event for fraud check", error_message = ?er);
}
Ok(frm)
}
async fn update_fraud_check_response_with_attempt_id(
&self,
this: FraudCheck,
fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, StorageError> {
let frm = self
.diesel_store
.update_fraud_check_response_with_attempt_id(this, fraud_check)
.await?;
if let Err(er) = self
.kafka_producer
.log_fraud_check(&frm, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er)
}
Ok(frm)
}
async fn find_fraud_check_by_payment_id(
&self,
payment_id: id_type::PaymentId,
merchant_id: id_type::MerchantId,
) -> CustomResult<FraudCheck, StorageError> {
let frm = self
.diesel_store
.find_fraud_check_by_payment_id(payment_id, merchant_id)
.await?;
if let Err(er) = self
.kafka_producer
.log_fraud_check(&frm, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er)
}
Ok(frm)
}
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: id_type::PaymentId,
merchant_id: id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, StorageError> {
let frm = self
.diesel_store
.find_fraud_check_by_payment_id_if_present(payment_id, merchant_id)
.await?;
if let Some(fraud_check) = frm.clone() {
if let Err(er) = self
.kafka_producer
.log_fraud_check(&fraud_check, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er);
}
}
Ok(frm)
}
}
#[async_trait::async_trait]
impl OrganizationInterface for KafkaStore {
async fn insert_organization(
&self,
organization: OrganizationNew,
) -> CustomResult<Organization, StorageError> {
self.diesel_store.insert_organization(organization).await
}
async fn find_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
) -> CustomResult<Organization, StorageError> {
self.diesel_store.find_organization_by_org_id(org_id).await
}
async fn update_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
update: OrganizationUpdate,
) -> CustomResult<Organization, StorageError> {
self.diesel_store
.update_organization_by_org_id(org_id, update)
.await
}
}
| {
"crate": "router",
"file": "crates/router/src/db.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8645521796716540257 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/compatibility/stripe/errors.rs
// Contains: 0 structs, 2 enums
use common_utils::{errors::ErrorSwitch, id_type};
use hyperswitch_domain_models::errors::api_error_response as errors;
use crate::core::errors::CustomersErrorResponse;
#[derive(Debug, router_derive::ApiError, Clone)]
#[error(error_type_enum = StripeErrorType)]
pub enum StripeErrorCode {
/*
"error": {
"message": "Invalid API Key provided: sk_jkjgs****nlgs",
"type": "invalid_request_error"
}
*/
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_01",
message = "Invalid API Key provided"
)]
Unauthorized,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")]
InvalidRequestUrl,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")]
ParameterMissing { field_name: String, param: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown",
message = "{field_name} contains invalid data. Expected format is {expected_format}."
)]
ParameterUnknown {
field_name: String,
expected_format: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")]
RefundAmountExceedsPaymentAmount { param: String },
#[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")]
PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")]
PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")]
DisputeFailed { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")]
ExpiredCard,
#[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")]
InvalidCardType,
#[error(
error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token",
message = "Invalid {wallet_name} wallet token"
)]
InvalidWalletToken { wallet_name: String },
#[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")]
RefundFailed, // stripe error code
#[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")]
PayoutFailed,
#[error(error_type = StripeErrorType::ApiError, code = "external_vault_failed", message = "external vault has failed")]
ExternalVaultFailed,
#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]
InternalServerError,
#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]
DuplicateRefundRequest,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")]
MandateActive,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")]
CustomerRedacted,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")]
DuplicateCustomer,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")]
RefundNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")]
ClientSecretNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")]
CustomerNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")]
ConfigNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")]
DuplicateConfig,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")]
PaymentNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")]
PaymentMethodNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")]
GenericNotFoundError { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")]
GenericDuplicateError { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")]
MerchantAccountNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")]
ResourceIdNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")]
MerchantConnectorAccountNotFound { id: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")]
MerchantConnectorAccountDisabled,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")]
MandateNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")]
ApiKeyNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")]
PayoutNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")]
EventNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")]
DuplicatePayout { payout_id: id_type::PayoutId },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")]
ReturnUrlUnavailable,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")]
DuplicateMerchantAccount,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
DuplicateMerchantConnectorAccount {
profile_id: String,
connector_label: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")]
DuplicatePaymentMethod,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")]
SerdeQsError {
error_message: String,
param: Option<String>,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")]
PaymentIntentInvalidParameter { param: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_05",
message = "{message}"
)]
InvalidRequestData { message: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_10",
message = "{message}"
)]
PreconditionFailed { message: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "The payment has not succeeded yet"
)]
PaymentFailed,
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "The verification did not succeeded"
)]
VerificationFailed { data: Option<serde_json::Value> },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "Reached maximum refund attempts"
)]
MaximumRefundCount,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")]
DuplicateMandate,
#[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")]
SuccessfulPaymentNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")]
AddressNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")]
PaymentIntentUnexpectedState {
current_flow: String,
field_name: String,
current_value: String,
states: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")]
PaymentIntentMandateInvalid { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")]
DuplicatePayment { payment_id: id_type::PaymentId },
#[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")]
ExternalConnectorError {
code: String,
message: String,
connector: String,
status_code: u16,
},
#[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")]
PaymentBlockedError {
code: u16,
message: String,
status: String,
reason: String,
},
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")]
IncorrectConnectorNameGiven,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")]
ResourceMissing { object: String, id: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")]
FileValidationFailed,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")]
MissingFile,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")]
MissingFilePurpose,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")]
MissingFileContentType,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")]
MissingDisputeId,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")]
FileNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")]
FileNotAvailable,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")]
FileProviderNotSupported,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")]
WebhookProcessingError,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")]
PaymentMethodUnactivated,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")]
HyperswitchUnprocessableEntity { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")]
CurrencyNotSupported { message: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")]
PaymentLinkNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")]
LockTimeout,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")]
InvalidConnectorConfiguration { config: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")]
LinkConfigurationError { message: String },
#[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")]
IntegrityCheckFailed {
reason: String,
field_names: String,
connector_transaction_id: Option<String>,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")]
InvalidTenant,
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")]
AmountConversionFailed { amount_type: &'static str },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")]
PlatformBadRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")]
PlatformUnauthorizedRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")]
ProfileAcquirerNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")]
SubscriptionError { operation: String },
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
/*
AccountCountryInvalidAddress,
AccountErrorCountryChangeRequiresAdditionalSteps,
AccountInformationMismatch,
AccountInvalid,
AccountNumberInvalid,
AcssDebitSessionIncomplete,
AlipayUpgradeRequired,
AmountTooLarge,
AmountTooSmall,
ApiKeyExpired,
AuthenticationRequired,
BalanceInsufficient,
BankAccountBadRoutingNumbers,
BankAccountDeclined,
BankAccountExists,
BankAccountUnusable,
BankAccountUnverified,
BankAccountVerificationFailed,
BillingInvalidMandate,
BitcoinUpgradeRequired,
CardDeclineRateLimitExceeded,
CardDeclined,
CardholderPhoneNumberRequired,
ChargeAlreadyCaptured,
ChargeAlreadyRefunded,
ChargeDisputed,
ChargeExceedsSourceLimit,
ChargeExpiredForCapture,
ChargeInvalidParameter,
ClearingCodeUnsupported,
CountryCodeInvalid,
CountryUnsupported,
CouponExpired,
CustomerMaxPaymentMethods,
CustomerMaxSubscriptions,
DebitNotAuthorized,
EmailInvalid,
ExpiredCard,
IdempotencyKeyInUse,
IncorrectAddress,
IncorrectCvc,
IncorrectNumber,
IncorrectZip,
InstantPayoutsConfigDisabled,
InstantPayoutsCurrencyDisabled,
InstantPayoutsLimitExceeded,
InstantPayoutsUnsupported,
InsufficientFunds,
IntentInvalidState,
IntentVerificationMethodMissing,
InvalidCardType,
InvalidCharacters,
InvalidChargeAmount,
InvalidCvc,
InvalidExpiryMonth,
InvalidExpiryYear,
InvalidNumber,
InvalidSourceUsage,
InvoiceNoCustomerLineItems,
InvoiceNoPaymentMethodTypes,
InvoiceNoSubscriptionLineItems,
InvoiceNotEditable,
InvoiceOnBehalfOfNotEditable,
InvoicePaymentIntentRequiresAction,
InvoiceUpcomingNone,
LivemodeMismatch,
LockTimeout,
Missing,
NoAccount,
NotAllowedOnStandardAccount,
OutOfInventory,
ParameterInvalidEmpty,
ParameterInvalidInteger,
ParameterInvalidStringBlank,
ParameterInvalidStringEmpty,
ParametersExclusive,
PaymentIntentActionRequired,
PaymentIntentIncompatiblePaymentMethod,
PaymentIntentInvalidParameter,
PaymentIntentKonbiniRejectedConfirmationNumber,
PaymentIntentPaymentAttemptExpired,
PaymentIntentUnexpectedState,
PaymentMethodBankAccountAlreadyVerified,
PaymentMethodBankAccountBlocked,
PaymentMethodBillingDetailsAddressMissing,
PaymentMethodCurrencyMismatch,
PaymentMethodInvalidParameter,
PaymentMethodInvalidParameterTestmode,
PaymentMethodMicrodepositFailed,
PaymentMethodMicrodepositVerificationAmountsInvalid,
PaymentMethodMicrodepositVerificationAmountsMismatch,
PaymentMethodMicrodepositVerificationAttemptsExceeded,
PaymentMethodMicrodepositVerificationDescriptorCodeMismatch,
PaymentMethodMicrodepositVerificationTimeout,
PaymentMethodProviderDecline,
PaymentMethodProviderTimeout,
PaymentMethodUnexpectedState,
PaymentMethodUnsupportedType,
PayoutsNotAllowed,
PlatformAccountRequired,
PlatformApiKeyExpired,
PostalCodeInvalid,
ProcessingError,
ProductInactive,
RateLimit,
ReferToCustomer,
RefundDisputedPayment,
ResourceAlreadyExists,
ResourceMissing,
ReturnIntentAlreadyProcessed,
RoutingNumberInvalid,
SecretKeyRequired,
SepaUnsupportedAccount,
SetupAttemptFailed,
SetupIntentAuthenticationFailure,
SetupIntentInvalidParameter,
SetupIntentSetupAttemptExpired,
SetupIntentUnexpectedState,
ShippingCalculationFailed,
SkuInactive,
StateUnsupported,
StatusTransitionInvalid,
TaxIdInvalid,
TaxesCalculationFailed,
TerminalLocationCountryUnsupported,
TestmodeChargesOnly,
TlsVersionUnsupported,
TokenInUse,
TransferSourceBalanceParametersMismatch,
TransfersNotAllowed,
*/
}
impl ::core::fmt::Display for StripeErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{{\"error\": {}}}",
serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
)
}
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::enum_variant_names)]
pub enum StripeErrorType {
ApiError,
CardError,
InvalidRequestError,
ConnectorError,
HyperswitchError,
}
impl From<errors::ApiErrorResponse> for StripeErrorCode {
fn from(value: errors::ApiErrorResponse) -> Self {
match value {
errors::ApiErrorResponse::Unauthorized
| errors::ApiErrorResponse::InvalidJwtToken
| errors::ApiErrorResponse::GenericUnauthorized { .. }
| errors::ApiErrorResponse::AccessForbidden { .. }
| errors::ApiErrorResponse::InvalidCookie
| errors::ApiErrorResponse::InvalidEphemeralKey
| errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized,
errors::ApiErrorResponse::InvalidRequestUrl
| errors::ApiErrorResponse::InvalidHttpMethod
| errors::ApiErrorResponse::InvalidCardIin
| errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl,
errors::ApiErrorResponse::MissingRequiredField { field_name } => {
Self::ParameterMissing {
field_name: field_name.to_string(),
param: field_name.to_string(),
}
}
errors::ApiErrorResponse::UnprocessableEntity { message } => {
Self::HyperswitchUnprocessableEntity { message }
}
errors::ApiErrorResponse::MissingRequiredFields { field_names } => {
// Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String
Self::ParameterMissing {
field_name: field_names.clone().join(", "),
param: field_names.clone().join(", "),
}
}
errors::ApiErrorResponse::GenericNotFoundError { message } => {
Self::GenericNotFoundError { message }
}
errors::ApiErrorResponse::GenericDuplicateError { message } => {
Self::GenericDuplicateError { message }
}
// parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff
errors::ApiErrorResponse::InvalidDataFormat {
field_name,
expected_format,
} => Self::ParameterUnknown {
field_name,
expected_format,
},
errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => {
Self::RefundAmountExceedsPaymentAmount {
param: "amount".to_owned(),
}
}
errors::ApiErrorResponse::PaymentAuthorizationFailed { data }
| errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => {
Self::PaymentIntentAuthenticationFailure { data }
}
errors::ApiErrorResponse::VerificationFailed { data } => {
Self::VerificationFailed { data }
}
errors::ApiErrorResponse::PaymentCaptureFailed { data } => {
Self::PaymentIntentPaymentAttemptFailed { data }
}
errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data },
errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard,
errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed,
errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map
errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed,
errors::ApiErrorResponse::ExternalVaultFailed => Self::ExternalVaultFailed,
errors::ApiErrorResponse::MandateUpdateFailed
| errors::ApiErrorResponse::MandateSerializationFailed
| errors::ApiErrorResponse::MandateDeserializationFailed
| errors::ApiErrorResponse::InternalServerError
| errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code
errors::ApiErrorResponse::ExternalConnectorError {
code,
message,
connector,
status_code,
..
} => Self::ExternalConnectorError {
code,
message,
connector,
status_code,
},
errors::ApiErrorResponse::IncorrectConnectorNameGiven => {
Self::IncorrectConnectorNameGiven
}
errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code
errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code
errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code
errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code
errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest,
errors::ApiErrorResponse::DuplicatePayout { payout_id } => {
Self::DuplicatePayout { payout_id }
}
errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound,
errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound,
errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound,
errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound,
errors::ApiErrorResponse::ClientSecretNotGiven
| errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound,
errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound,
errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound,
errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound,
errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => {
Self::MerchantConnectorAccountNotFound { id }
}
errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound,
errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound,
errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound,
errors::ApiErrorResponse::EventNotFound => Self::EventNotFound,
errors::ApiErrorResponse::MandateValidationFailed { reason } => {
Self::PaymentIntentMandateInvalid { message: reason }
}
errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable,
errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount,
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
profile_id,
connector_label,
} => Self::DuplicateMerchantConnectorAccount {
profile_id,
connector_label,
},
errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod,
errors::ApiErrorResponse::PaymentBlockedError {
code,
message,
status,
reason,
} => Self::PaymentBlockedError {
code,
message,
status,
reason,
},
errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter {
param: "client_secret".to_owned(),
},
errors::ApiErrorResponse::InvalidRequestData { message } => {
Self::InvalidRequestData { message }
}
errors::ApiErrorResponse::PreconditionFailed { message } => {
Self::PreconditionFailed { message }
}
errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing {
field_name: field_name.to_string(),
param: field_name.to_string(),
},
errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount,
errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed,
errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate,
errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound,
errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound,
errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized,
errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError,
errors::ApiErrorResponse::MandatePaymentDataMismatch { .. } => Self::PlatformBadRequest,
errors::ApiErrorResponse::MaxFieldLengthViolated { .. } => Self::PlatformBadRequest,
errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow,
field_name,
current_value,
states,
} => Self::PaymentIntentUnexpectedState {
current_flow,
field_name,
current_value,
states,
},
errors::ApiErrorResponse::DuplicatePayment { payment_id } => {
Self::DuplicatePayment { payment_id }
}
errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing {
object: "dispute".to_owned(),
id: dispute_id,
},
errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing {
object: "authentication".to_owned(),
id,
},
errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing {
object: "business_profile".to_owned(),
id,
},
errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing {
object: "poll".to_owned(),
id,
},
errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => {
Self::InternalServerError
}
errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed,
errors::ApiErrorResponse::MissingFile => Self::MissingFile,
errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose,
errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType,
errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId,
errors::ApiErrorResponse::FileNotFound => Self::FileNotFound,
errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable,
errors::ApiErrorResponse::MerchantConnectorAccountDisabled => {
Self::MerchantConnectorAccountDisabled
}
errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError,
errors::ApiErrorResponse::CurrencyNotSupported { message } => {
Self::CurrencyNotSupported { message }
}
errors::ApiErrorResponse::FileProviderNotSupported { .. } => {
Self::FileProviderNotSupported
}
errors::ApiErrorResponse::WebhookBadRequest
| errors::ApiErrorResponse::WebhookResourceNotFound
| errors::ApiErrorResponse::WebhookProcessingFailure
| errors::ApiErrorResponse::WebhookAuthenticationFailed
| errors::ApiErrorResponse::WebhookUnprocessableEntity
| errors::ApiErrorResponse::WebhookInvalidMerchantSecret => {
Self::WebhookProcessingError
}
errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => {
Self::PaymentMethodUnactivated
}
errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated,
errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => {
Self::InvalidConnectorConfiguration { config }
}
errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed,
errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed,
errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => {
Self::InvalidWalletToken { wallet_name }
}
errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound,
errors::ApiErrorResponse::LinkConfigurationError { message } => {
Self::LinkConfigurationError { message }
}
errors::ApiErrorResponse::IntegrityCheckFailed {
reason,
field_names,
connector_transaction_id,
} => Self::IntegrityCheckFailed {
reason,
field_names,
connector_transaction_id,
},
errors::ApiErrorResponse::InvalidTenant { tenant_id: _ }
| errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant,
errors::ApiErrorResponse::AmountConversionFailed { amount_type } => {
Self::AmountConversionFailed { amount_type }
}
errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest,
errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest,
errors::ApiErrorResponse::ProfileAcquirerNotFound { .. } => {
Self::ProfileAcquirerNotFound
}
errors::ApiErrorResponse::TokenizationRecordNotFound { id } => Self::ResourceMissing {
object: "tokenization record".to_owned(),
id,
},
errors::ApiErrorResponse::SubscriptionError { operation } => {
Self::SubscriptionError { operation }
}
}
}
}
impl actix_web::ResponseError for StripeErrorCode {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED,
Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND,
Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => {
StatusCode::UNPROCESSABLE_ENTITY
}
Self::ParameterMissing { .. }
| Self::RefundAmountExceedsPaymentAmount { .. }
| Self::PaymentIntentAuthenticationFailure { .. }
| Self::PaymentIntentPaymentAttemptFailed { .. }
| Self::ExpiredCard
| Self::InvalidCardType
| Self::DuplicateRefundRequest
| Self::DuplicatePayout { .. }
| Self::RefundNotFound
| Self::CustomerNotFound
| Self::ConfigNotFound
| Self::DuplicateConfig
| Self::ClientSecretNotFound
| Self::PaymentNotFound
| Self::PaymentMethodNotFound
| Self::MerchantAccountNotFound
| Self::MerchantConnectorAccountNotFound { .. }
| Self::MerchantConnectorAccountDisabled
| Self::MandateNotFound
| Self::ApiKeyNotFound
| Self::PayoutNotFound
| Self::EventNotFound
| Self::DuplicateMerchantAccount
| Self::DuplicateMerchantConnectorAccount { .. }
| Self::DuplicatePaymentMethod
| Self::PaymentFailed
| Self::VerificationFailed { .. }
| Self::DisputeFailed { .. }
| Self::MaximumRefundCount
| Self::PaymentIntentInvalidParameter { .. }
| Self::SerdeQsError { .. }
| Self::InvalidRequestData { .. }
| Self::InvalidWalletToken { .. }
| Self::PreconditionFailed { .. }
| Self::DuplicateMandate
| Self::SuccessfulPaymentNotFound
| Self::AddressNotFound
| Self::ResourceIdNotFound
| Self::PaymentIntentMandateInvalid { .. }
| Self::PaymentIntentUnexpectedState { .. }
| Self::DuplicatePayment { .. }
| Self::GenericDuplicateError { .. }
| Self::IncorrectConnectorNameGiven
| Self::ResourceMissing { .. }
| Self::FileValidationFailed
| Self::MissingFile
| Self::MissingFileContentType
| Self::MissingFilePurpose
| Self::MissingDisputeId
| Self::FileNotFound
| Self::FileNotAvailable
| Self::FileProviderNotSupported
| Self::CurrencyNotSupported { .. }
| Self::DuplicateCustomer
| Self::PaymentMethodUnactivated
| Self::InvalidConnectorConfiguration { .. }
| Self::CurrencyConversionFailed
| Self::PaymentMethodDeleteFailed
| Self::ExtendedCardInfoNotFound
| Self::PlatformBadRequest
| Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::PayoutFailed
| Self::PaymentLinkNotFound
| Self::InternalServerError
| Self::MandateActive
| Self::CustomerRedacted
| Self::WebhookProcessingError
| Self::InvalidTenant
| Self::ExternalVaultFailed
| Self::AmountConversionFailed { .. }
| Self::SubscriptionError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE,
Self::ExternalConnectorError { status_code, .. } => {
StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR,
Self::PaymentBlockedError { code, .. } => {
StatusCode::from_u16(*code).unwrap_or(StatusCode::OK)
}
Self::LockTimeout => StatusCode::LOCKED,
Self::ProfileAcquirerNotFound => StatusCode::NOT_FOUND,
}
}
fn error_response(&self) -> actix_web::HttpResponse {
use actix_web::http::header;
actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.body(self.to_string())
}
}
impl From<serde_qs::Error> for StripeErrorCode {
fn from(item: serde_qs::Error) -> Self {
match item {
serde_qs::Error::Custom(s) => Self::SerdeQsError {
error_message: s,
param: None,
},
serde_qs::Error::Parse(param, position) => Self::SerdeQsError {
error_message: format!(
"parsing failed with error: '{param}' at position: {position}"
),
param: Some(param),
},
serde_qs::Error::Unsupported => Self::SerdeQsError {
error_message: "Given request format is not supported".to_owned(),
param: None,
},
serde_qs::Error::FromUtf8(_) => Self::SerdeQsError {
error_message: "Failed to parse request to from utf-8".to_owned(),
param: None,
},
serde_qs::Error::Io(_) => Self::SerdeQsError {
error_message: "Failed to parse request".to_owned(),
param: None,
},
serde_qs::Error::ParseInt(_) => Self::SerdeQsError {
error_message: "Failed to parse integer in request".to_owned(),
param: None,
},
serde_qs::Error::Utf8(_) => Self::SerdeQsError {
error_message: "Failed to convert utf8 to string".to_owned(),
param: None,
},
}
}
}
impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse {
fn switch(&self) -> StripeErrorCode {
self.clone().into()
}
}
impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {}
impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse {
fn switch(&self) -> StripeErrorCode {
use StripeErrorCode as SC;
match self {
Self::CustomerRedacted => SC::CustomerRedacted,
Self::InternalServerError => SC::InternalServerError,
Self::InvalidRequestData { message } => SC::InvalidRequestData {
message: message.clone(),
},
Self::MandateActive => SC::MandateActive,
Self::CustomerNotFound => SC::CustomerNotFound,
Self::CustomerAlreadyExists => SC::DuplicateCustomer,
}
}
}
| {
"crate": "router",
"file": "crates/router/src/compatibility/stripe/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_6947740444299058765 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/types/domain/user/decision_manager.rs
// Contains: 0 structs, 4 enums
use common_enums::TokenPurpose;
use common_utils::{id_type, types::user::LineageContext};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
user_role::UserRole,
};
use error_stack::ResultExt;
use masking::Secret;
use router_env::logger;
use super::UserFromStorage;
use crate::{
core::errors::{UserErrors, UserResult},
db::user_role::ListUserRolesByUserIdPayload,
routes::SessionState,
services::authentication as auth,
utils,
};
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum UserFlow {
SPTFlow(SPTFlow),
JWTFlow(JWTFlow),
}
impl UserFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
Self::SPTFlow(flow) => flow.is_required(user, path, state, user_tenant_id).await,
Self::JWTFlow(flow) => flow.is_required(user, state).await,
}
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum SPTFlow {
AuthSelect,
SSO,
TOTP,
VerifyEmail,
AcceptInvitationFromEmail,
ForceSetPassword,
MerchantSelect,
ResetPassword,
}
impl SPTFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
// Auth
Self::AuthSelect => Ok(true),
Self::SSO => Ok(true),
// TOTP
Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)),
// Main email APIs
Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
Self::VerifyEmail => Ok(true),
// Final Checks
Self::ForceSetPassword => user
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
Self::MerchantSelect => Ok(state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user.get_user_id(),
tenant_id: user_tenant_id,
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.is_empty()),
}
}
pub async fn generate_spt(
self,
state: &SessionState,
next_flow: &NextFlow,
) -> UserResult<Secret<String>> {
auth::SinglePurposeToken::new_token(
next_flow.user.get_user_id().to_string(),
self.into(),
next_flow.origin.clone(),
&state.conf,
next_flow.path.to_vec(),
Some(state.tenant.tenant_id.clone()),
)
.await
.map(|token| token.into())
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum JWTFlow {
UserInfo,
}
impl JWTFlow {
async fn is_required(
&self,
_user: &UserFromStorage,
_state: &SessionState,
) -> UserResult<bool> {
Ok(true)
}
pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
let user_id = next_flow.user.get_user_id();
// Fetch lineage context from DB
let lineage_context_from_db = state
.global_store
.find_user_by_id(user_id)
.await
.inspect_err(|e| {
logger::error!(
"Failed to fetch lineage context from DB for user {}: {:?}",
user_id,
e
)
})
.ok()
.and_then(|user| user.lineage_context);
let new_lineage_context = match lineage_context_from_db {
Some(ctx) => {
let tenant_id = ctx.tenant_id.clone();
let user_role_match_v2 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V2,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V2 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v2 {
ctx
} else {
let user_role_match_v1 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V1,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V1 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v1 {
ctx
} else {
// fallback to default lineage if cached context is invalid
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
}
}
None =>
// no cached context found
{
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
};
utils::user::spawn_async_lineage_context_update_to_db(
state,
user_id,
new_lineage_context.clone(),
);
auth::AuthToken::new_token(
new_lineage_context.user_id,
new_lineage_context.merchant_id,
new_lineage_context.role_id,
&state.conf,
new_lineage_context.org_id,
new_lineage_context.profile_id,
Some(new_lineage_context.tenant_id),
)
.await
.map(|token| token.into())
}
pub async fn resolve_lineage_from_user_role(
state: &SessionState,
user_role: &UserRole,
user_id: &str,
) -> UserResult<LineageContext> {
let org_id = utils::user_role::get_single_org_id(state, user_role).await?;
let merchant_id =
utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?;
let profile_id =
utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?;
Ok(LineageContext {
user_id: user_id.to_string(),
org_id,
merchant_id,
profile_id,
role_id: user_role.role_id.clone(),
tenant_id: user_role.tenant_id.clone(),
})
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
#[serde(rename = "sign_in_with_sso")]
SignInWithSSO,
SignIn,
SignUp,
MagicLink,
VerifyEmail,
AcceptInvitationFromEmail,
ResetPassword,
}
impl Origin {
fn get_flows(&self) -> &'static [UserFlow] {
match self {
Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW,
Self::SignIn => &SIGNIN_FLOW,
Self::SignUp => &SIGNUP_FLOW,
Self::VerifyEmail => &VERIFY_EMAIL_FLOW,
Self::MagicLink => &MAGIC_LINK_FLOW,
Self::AcceptInvitationFromEmail => &ACCEPT_INVITATION_FROM_EMAIL_FLOW,
Self::ResetPassword => &RESET_PASSWORD_FLOW,
}
}
}
const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const SIGNIN_FLOW: [UserFlow; 4] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const SIGNUP_FLOW: [UserFlow; 4] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const MAGIC_LINK_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [
UserFlow::SPTFlow(SPTFlow::AuthSelect),
UserFlow::SPTFlow(SPTFlow::SSO),
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const RESET_PASSWORD_FLOW: [UserFlow; 2] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ResetPassword),
];
pub struct CurrentFlow {
origin: Origin,
current_flow_index: usize,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
}
impl CurrentFlow {
pub fn new(
token: auth::UserFromSinglePurposeToken,
current_flow: UserFlow,
) -> UserResult<Self> {
let flows = token.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == ¤t_flow)
.ok_or(UserErrors::InternalServerError)?;
let mut path = token.path;
path.push(current_flow.into());
Ok(Self {
origin: token.origin,
current_flow_index: index,
path,
tenant_id: token.tenant_id,
})
}
pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> {
let flows = self.origin.get_flows();
let remaining_flows = flows.iter().skip(self.current_flow_index + 1);
for flow in remaining_flows {
if flow
.is_required(
&user,
&self.path,
state,
self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await?
{
return Ok(NextFlow {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: self.tenant_id,
});
}
}
Err(UserErrors::InternalServerError.into())
}
}
pub struct NextFlow {
origin: Origin,
next_flow: UserFlow,
user: UserFromStorage,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
}
impl NextFlow {
pub async fn from_origin(
origin: Origin,
user: UserFromStorage,
state: &SessionState,
) -> UserResult<Self> {
let flows = origin.get_flows();
let path = vec![];
for flow in flows {
if flow
.is_required(&user, &path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin,
next_flow: *flow,
user,
path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
pub fn get_flow(&self) -> UserFlow {
self.next_flow
}
pub async fn get_token(&self, state: &SessionState) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
let user_role = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: self.user.get_user_id(),
tenant_id: self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?;
utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await;
jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
pub async fn get_token_with_user_role(
&self,
state: &SessionState,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
utils::user_role::set_role_info_in_cache_by_user_role(state, user_role).await;
jwt_flow.generate_jwt(state, self, user_role).await
}
}
}
pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> {
let flows = self.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == &self.get_flow())
.ok_or(UserErrors::InternalServerError)?;
let remaining_flows = flows.iter().skip(index + 1);
for flow in remaining_flows {
if flow
.is_required(&user, &self.path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
}
impl From<UserFlow> for TokenPurpose {
fn from(value: UserFlow) -> Self {
match value {
UserFlow::SPTFlow(flow) => flow.into(),
UserFlow::JWTFlow(flow) => flow.into(),
}
}
}
impl From<SPTFlow> for TokenPurpose {
fn from(value: SPTFlow) -> Self {
match value {
SPTFlow::AuthSelect => Self::AuthSelect,
SPTFlow::SSO => Self::SSO,
SPTFlow::TOTP => Self::TOTP,
SPTFlow::VerifyEmail => Self::VerifyEmail,
SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
SPTFlow::MerchantSelect => Self::AcceptInvite,
SPTFlow::ResetPassword => Self::ResetPassword,
SPTFlow::ForceSetPassword => Self::ForceSetPassword,
}
}
}
impl From<JWTFlow> for TokenPurpose {
fn from(value: JWTFlow) -> Self {
match value {
JWTFlow::UserInfo => Self::UserInfo,
}
}
}
impl From<SPTFlow> for UserFlow {
fn from(value: SPTFlow) -> Self {
Self::SPTFlow(value)
}
}
impl From<JWTFlow> for UserFlow {
fn from(value: JWTFlow) -> Self {
Self::JWTFlow(value)
}
}
| {
"crate": "router",
"file": "crates/router/src/types/domain/user/decision_manager.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 4,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_8879184066397108941 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/routing.rs
// Contains: 0 structs, 2 enums
mod transformers;
pub mod utils;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use std::collections::hash_map;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use std::hash::{Hash, Hasher};
use std::{collections::HashMap, str::FromStr, sync::Arc};
#[cfg(feature = "v1")]
use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use common_types::payments as common_payments_types;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::AsyncExt;
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use euclid::{
backend::{self, inputs as dsl_inputs, EuclidBackend},
dssa::graph::{self as euclid_graph, CgraphExt},
enums as euclid_enums,
frontend::{ast, dir as euclid_dir},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting, DynamicRoutingError,
};
use hyperswitch_domain_models::address::Address;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine};
use kgraph_utils::{
mca as mca_graph,
transformers::{IntoContext, IntoDirValue},
types::CountryCurrencyFilter,
};
use masking::{PeekInterface, Secret};
use rand::distributions::{self, Distribution};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use rand::SeedableRng;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};
#[cfg(feature = "v2")]
use crate::core::admin;
#[cfg(feature = "payouts")]
use crate::core::payouts;
#[cfg(feature = "v1")]
use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::routes::app::SessionStateInfo;
use crate::{
core::{
errors, errors as oss_errors,
payments::{
routing::utils::DecisionEngineApiHandler, OperationSessionGetters,
OperationSessionSetters,
},
routing,
},
logger, services,
types::{
api::{self, routing as routing_types},
domain, storage as oss_storage,
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{OptionExt, ValueExt},
SessionState,
};
pub enum CachedAlgorithm {
Single(Box<routing_types::RoutableConnectorChoice>),
Priority(Vec<routing_types::RoutableConnectorChoice>),
VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>),
Advanced(backend::VirInterpreterBackend<ConnectorSelection>),
}
#[cfg(feature = "v1")]
pub struct SessionFlowRoutingInput<'a> {
pub state: &'a SessionState,
pub country: Option<CountryAlpha2>,
pub key_store: &'a domain::MerchantKeyStore,
pub merchant_account: &'a domain::MerchantAccount,
pub payment_attempt: &'a oss_storage::PaymentAttempt,
pub payment_intent: &'a oss_storage::PaymentIntent,
pub chosen: api::SessionConnectorDatas,
}
#[cfg(feature = "v2")]
pub struct SessionFlowRoutingInput<'a> {
pub country: Option<CountryAlpha2>,
pub payment_intent: &'a oss_storage::PaymentIntent,
pub chosen: api::SessionConnectorDatas,
}
#[allow(dead_code)]
#[cfg(feature = "v1")]
pub struct SessionRoutingPmTypeInput<'a> {
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
attempt_id: &'a str,
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
profile_id: &'a common_utils::id_type::ProfileId,
}
#[cfg(feature = "v2")]
pub struct SessionRoutingPmTypeInput<'a> {
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
profile_id: &'a common_utils::id_type::ProfileId,
}
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum MerchantAccountRoutingAlgorithm {
V1(routing_types::RoutingAlgorithmRef),
}
#[cfg(feature = "v1")]
impl Default for MerchantAccountRoutingAlgorithm {
fn default() -> Self {
Self::V1(routing_types::RoutingAlgorithmRef::default())
}
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum MerchantAccountRoutingAlgorithm {
V1(Option<common_utils::id_type::RoutingId>),
}
#[cfg(feature = "payouts")]
pub fn make_dsl_input_for_payouts(
payout_data: &payouts::PayoutData,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let metadata = payout_data
.payouts
.metadata
.clone()
.map(|val| val.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payouts")
.unwrap_or(None);
let payment = dsl_inputs::PaymentInput {
amount: payout_data.payouts.amount,
card_bin: None,
currency: payout_data.payouts.destination_currency,
authentication_type: None,
capture_method: None,
business_country: payout_data
.payout_attempt
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payout_data
.billing_address
.as_ref()
.and_then(|ba| ba.address.as_ref())
.and_then(|addr| addr.country)
.map(api_enums::Country::from_alpha2),
business_label: payout_data.payout_attempt.business_label.clone(),
setup_future_usage: None,
};
let payment_method = dsl_inputs::PaymentMethodInput {
payment_method: payout_data
.payouts
.payout_type
.map(api_enums::PaymentMethod::foreign_from),
payment_method_type: payout_data
.payout_method_data
.as_ref()
.map(api_enums::PaymentMethodType::foreign_from)
.or_else(|| {
payout_data.payment_method.as_ref().and_then(|pm| {
#[cfg(feature = "v1")]
{
pm.payment_method_type
}
#[cfg(feature = "v2")]
{
pm.payment_method_subtype
}
})
}),
card_network: None,
};
Ok(dsl_inputs::BackendInput {
mandate,
metadata,
payment,
payment_method,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
})
}
#[cfg(feature = "v2")]
pub fn make_dsl_input(
payments_dsl_input: &routing::PaymentsDslInput<'_>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then(
|mandate_data| {
mandate_data
.customer_acceptance
.as_ref()
.map(|customer_accept| match customer_accept.acceptance_type {
common_payments_types::AcceptanceType::Online => {
euclid_enums::MandateAcceptanceType::Online
}
common_payments_types::AcceptanceType::Offline => {
euclid_enums::MandateAcceptanceType::Offline
}
})
},
),
mandate_type: payments_dsl_input
.setup_mandate
.as_ref()
.and_then(|mandate_data| {
mandate_data
.mandate_type
.clone()
.map(|mandate_type| match mandate_type {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => {
euclid_enums::MandateType::SingleUse
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => {
euclid_enums::MandateType::MultiUse
}
})
}),
payment_type: Some(
if payments_dsl_input
.recurring_details
.as_ref()
.is_some_and(|data| {
matches!(
data,
api_models::mandates::RecurringDetails::ProcessorPaymentToken(_)
)
})
{
euclid_enums::PaymentType::PptMandate
} else {
payments_dsl_input.setup_mandate.map_or_else(
|| euclid_enums::PaymentType::NonMandate,
|_| euclid_enums::PaymentType::SetupMandate,
)
},
),
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type),
payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype),
card_network: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => card.card_network.clone(),
_ => None,
}),
};
let payment_input = dsl_inputs::PaymentInput {
amount: payments_dsl_input
.payment_attempt
.amount_details
.get_net_amount(),
card_bin: payments_dsl_input.payment_method_data.as_ref().and_then(
|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()),
_ => None,
},
),
currency: payments_dsl_input.currency,
authentication_type: Some(payments_dsl_input.payment_attempt.authentication_type),
capture_method: Some(payments_dsl_input.payment_intent.capture_method),
business_country: None,
billing_country: payments_dsl_input
.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address_details| address_details.country)
.map(api_enums::Country::from_alpha2),
business_label: None,
setup_future_usage: Some(payments_dsl_input.payment_intent.setup_future_usage),
};
let metadata = payments_dsl_input
.payment_intent
.metadata
.clone()
.map(|value| value.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
Ok(dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
})
}
#[cfg(feature = "v1")]
pub fn make_dsl_input(
payments_dsl_input: &routing::PaymentsDslInput<'_>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then(
|mandate_data| {
mandate_data
.customer_acceptance
.as_ref()
.map(|cat| match cat.acceptance_type {
common_payments_types::AcceptanceType::Online => {
euclid_enums::MandateAcceptanceType::Online
}
common_payments_types::AcceptanceType::Offline => {
euclid_enums::MandateAcceptanceType::Offline
}
})
},
),
mandate_type: payments_dsl_input
.setup_mandate
.as_ref()
.and_then(|mandate_data| {
mandate_data.mandate_type.clone().map(|mt| match mt {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => {
euclid_enums::MandateType::SingleUse
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => {
euclid_enums::MandateType::MultiUse
}
})
}),
payment_type: Some(
if payments_dsl_input
.recurring_details
.as_ref()
.is_some_and(|data| {
matches!(
data,
api_models::mandates::RecurringDetails::ProcessorPaymentToken(_)
)
})
{
euclid_enums::PaymentType::PptMandate
} else {
payments_dsl_input.setup_mandate.map_or_else(
|| euclid_enums::PaymentType::NonMandate,
|_| euclid_enums::PaymentType::SetupMandate,
)
},
),
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: payments_dsl_input.payment_attempt.payment_method,
payment_method_type: payments_dsl_input.payment_attempt.payment_method_type,
card_network: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => card.card_network.clone(),
_ => None,
}),
};
let payment_input = dsl_inputs::PaymentInput {
amount: payments_dsl_input.payment_attempt.get_total_amount(),
card_bin: payments_dsl_input.payment_method_data.as_ref().and_then(
|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
Some(card.card_number.peek().chars().take(6).collect())
}
_ => None,
},
),
currency: payments_dsl_input.currency,
authentication_type: payments_dsl_input.payment_attempt.authentication_type,
capture_method: payments_dsl_input
.payment_attempt
.capture_method
.and_then(|cm| cm.foreign_into()),
business_country: payments_dsl_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payments_dsl_input
.address
.get_payment_method_billing()
.and_then(|bic| bic.address.as_ref())
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payments_dsl_input.payment_intent.business_label.clone(),
setup_future_usage: payments_dsl_input.payment_intent.setup_future_usage,
};
let metadata = payments_dsl_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
Ok(dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
})
}
pub async fn perform_static_routing_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: Option<&common_utils::id_type::RoutingId>,
business_profile: &domain::Profile,
transaction_data: &routing::TransactionData<'_>,
) -> RoutingResult<(
Vec<routing_types::RoutableConnectorChoice>,
Option<common_enums::RoutingApproach>,
)> {
logger::debug!("euclid_routing: performing routing for connector selection");
let get_merchant_fallback_config = || async {
#[cfg(feature = "v1")]
return routing::helpers::get_merchant_default_config(
&*state.clone().store,
business_profile.get_id().get_string_repr(),
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed);
#[cfg(feature = "v2")]
return admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed);
};
let algorithm_id = if let Some(id) = algorithm_id {
id
} else {
let fallback_config = get_merchant_fallback_config().await?;
logger::debug!("euclid_routing: active algorithm isn't present, default falling back");
return Ok((fallback_config, None));
};
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
let payment_id = match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_attempt
.payment_id
.clone()
.get_string_repr()
.to_string(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => payout_data
.payout_attempt
.payout_id
.get_string_repr()
.to_string(),
};
// Decision of de-routing is stored
let de_evaluated_connector = if !state.conf.open_router.static_routing_enabled {
logger::debug!("decision_engine_euclid: decision_engine routing not enabled");
Vec::default()
} else {
utils::decision_engine_routing(
state,
backend_input.clone(),
business_profile,
payment_id,
get_merchant_fallback_config().await?,
)
.await
.map_err(|e|
// errors are ignored as this is just for diff checking as of now (optional flow).
logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule")
)
.unwrap_or_default()
};
let (routable_connectors, routing_approach) = match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => (
vec![(**conn).clone()],
Some(common_enums::RoutingApproach::StraightThroughRouting),
),
CachedAlgorithm::Priority(plist) => (plist.clone(), None),
CachedAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
Some(common_enums::RoutingApproach::VolumeBasedRouting),
),
CachedAlgorithm::Advanced(interpreter) => (
execute_dsl_and_get_connector_v1(backend_input, interpreter)?,
Some(common_enums::RoutingApproach::RuleBasedRouting),
),
};
// Results are logged for diff(between legacy and decision_engine's euclid) and have parameters as:
// is_equal: verifies all output are matching in order,
// is_equal_length: matches length of both outputs (useful for verifying volume based routing
// results)
// de_response: response from the decision_engine's euclid
// hs_response: response from legacy_euclid
utils::compare_and_log_result(
de_evaluated_connector.clone(),
routable_connectors.clone(),
"evaluate_routing".to_string(),
);
Ok((
utils::select_routing_result(
state,
business_profile,
routable_connectors,
de_evaluated_connector,
)
.await,
routing_approach,
))
}
async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
}
#[cfg(feature = "payouts")]
common_enums::TransactionType::Payout => {
format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
common_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
}
};
let cached_algorithm = ROUTING_CACHE
.get_val::<Arc<CachedAlgorithm>>(CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await;
let algorithm = if let Some(algo) = cached_algorithm {
algo
} else {
refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await?
};
Ok(algorithm)
}
pub fn perform_straight_through_routing(
algorithm: &routing_types::StraightThroughAlgorithm,
creds_identifier: Option<&str>,
) -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>, bool)> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(conn) => {
(vec![(**conn).clone()], creds_identifier.is_none())
}
routing_types::StraightThroughAlgorithm::Priority(conns) => (conns.clone(), true),
routing_types::StraightThroughAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)
.attach_printable(
"Volume Split connector selection error in straight through routing",
)?,
true,
),
})
}
pub fn perform_routing_for_single_straight_through_algorithm(
algorithm: &routing_types::StraightThroughAlgorithm,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()],
routing_types::StraightThroughAlgorithm::Priority(_)
| routing_types::StraightThroughAlgorithm::VolumeSplit(_) => {
Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?
}
})
}
fn execute_dsl_and_get_connector_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let routing_output: routing_types::StaticRoutingAlgorithm = interpreter
.execute(backend_input)
.map(|out| out.connector_selection.foreign_into())
.change_context(errors::RoutingError::DslExecutionError)?;
Ok(match routing_output {
routing_types::StaticRoutingAlgorithm::Priority(plist) => plist,
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits)
.change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?,
_ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?,
})
}
pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let algorithm = {
let algorithm = state
.store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id)
.await
.change_context(errors::RoutingError::DslMissingInDb)?;
let algorithm: routing_types::StaticRoutingAlgorithm = algorithm
.algorithm_data
.parse_value("RoutingAlgorithm")
.change_context(errors::RoutingError::DslParsingError)?;
algorithm
};
let cached_algorithm = match algorithm {
routing_types::StaticRoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn),
routing_types::StaticRoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist),
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
CachedAlgorithm::VolumeSplit(splits)
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let interpreter = backend::VirInterpreterBackend::with_program(program)
.change_context(errors::RoutingError::DslBackendInitError)
.attach_printable("Error initializing DSL interpreter backend")?;
CachedAlgorithm::Advanced(interpreter)
}
api_models::routing::StaticRoutingAlgorithm::ThreeDsDecisionRule(_program) => {
Err(errors::RoutingError::InvalidRoutingAlgorithmStructure)
.attach_printable("Unsupported algorithm received")?
}
};
let arc_cached_algorithm = Arc::new(cached_algorithm);
ROUTING_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
arc_cached_algorithm.clone(),
)
.await;
Ok(arc_cached_algorithm)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub fn perform_dynamic_routing_volume_split(
splits: Vec<api_models::routing::RoutingVolumeSplit>,
rng_seed: Option<&str>,
) -> RoutingResult<api_models::routing::RoutingVolumeSplit> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let idx = if let Some(seed) = rng_seed {
let mut hasher = hash_map::DefaultHasher::new();
seed.hash(&mut hasher);
let hash = hasher.finish();
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash);
weighted_index.sample(&mut rng)
} else {
let mut rng = rand::thread_rng();
weighted_index.sample(&mut rng)
};
let routing_choice = *splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
Ok(routing_choice)
}
pub fn perform_volume_split(
mut splits: Vec<routing_types::ConnectorVolumeSplit>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let mut rng = rand::thread_rng();
let idx = weighted_index.sample(&mut rng);
splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
// Panic Safety: We have performed a `get(idx)` operation just above which will
// ensure that the index is always present, else throw an error.
let removed = splits.remove(idx);
splits.insert(0, removed);
Ok(splits.into_iter().map(|sp| sp.connector).collect())
}
// #[cfg(feature = "v1")]
pub async fn get_merchant_cgraph(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let merchant_id = &key_store.merchant_id;
let key = {
match transaction_type {
api_enums::TransactionType::Payment => {
format!(
"cgraph_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
format!(
"cgraph_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
}
};
let cached_cgraph = CGRAPH_CACHE
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>(
CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
},
)
.await;
let cgraph = if let Some(graph) = cached_cgraph {
graph
} else {
refresh_cgraph_cache(state, key_store, key.clone(), profile_id, transaction_type).await?
};
Ok(cgraph)
}
// #[cfg(feature = "v1")]
pub async fn refresh_cgraph_cache(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
&key_store.merchant_id,
false,
key_store,
)
.await
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
match transaction_type {
api_enums::TransactionType::Payment => {
merchant_connector_accounts.retain(|mca| {
mca.connector_type != storage_enums::ConnectorType::PaymentVas
&& mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth
&& mca.connector_type != storage_enums::ConnectorType::PayoutProcessor
&& mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor
});
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
merchant_connector_accounts
.retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor);
}
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
};
let connector_type = match transaction_type {
api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor,
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor,
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
};
let merchant_connector_accounts = merchant_connector_accounts
.filter_based_on_profile_and_connector_type(profile_id, connector_type);
let api_mcas = merchant_connector_accounts
.into_iter()
.map(admin_api::MerchantConnectorResponse::foreign_try_from)
.collect::<Result<Vec<_>, _>>()
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
let connector_configs = state
.conf
.pm_filters
.0
.clone()
.into_iter()
.filter(|(key, _)| key != "default")
.map(|(key, value)| {
let key = api_enums::RoutableConnectors::from_str(&key)
.map_err(|_| errors::RoutingError::InvalidConnectorName(key))?;
Ok((key, value.foreign_into()))
})
.collect::<Result<HashMap<_, _>, errors::RoutingError>>()?;
let default_configs = state
.conf
.pm_filters
.0
.get("default")
.cloned()
.map(ForeignFrom::foreign_from);
let config_pm_filters = CountryCurrencyFilter {
connector_configs,
default_configs,
};
let cgraph = Arc::new(
mca_graph::make_mca_graph(api_mcas, &config_pm_filters)
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)
.attach_printable("when construction cgraph")?,
);
CGRAPH_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
Arc::clone(&cgraph),
)
.await;
Ok(cgraph)
}
#[allow(clippy::too_many_arguments)]
pub async fn perform_cgraph_filtering(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
backend_input: dsl_inputs::BackendInput,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let context = euclid_graph::AnalysisContext::from_dir_values(
backend_input
.into_context()
.change_context(errors::RoutingError::KgraphAnalysisError)?,
);
let cached_cgraph = get_merchant_cgraph(state, key_store, profile_id, transaction_type).await?;
let mut final_selection = Vec::<routing_types::RoutableConnectorChoice>::new();
for choice in chosen {
let routable_connector = choice.connector;
let euclid_choice: ast::ConnectorChoice = choice.clone().foreign_into();
let dir_val = euclid_choice
.into_dir_value()
.change_context(errors::RoutingError::KgraphAnalysisError)?;
let cgraph_eligible = cached_cgraph
.check_value_validity(
dir_val,
&context,
&mut hyperswitch_constraint_graph::Memoization::new(),
&mut hyperswitch_constraint_graph::CycleCheck::new(),
None,
)
.change_context(errors::RoutingError::KgraphAnalysisError)?;
let filter_eligible =
eligible_connectors.is_none_or(|list| list.contains(&routable_connector));
if cgraph_eligible && filter_eligible {
final_selection.push(choice);
}
}
Ok(final_selection)
}
pub async fn perform_eligibility_analysis(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
chosen,
backend_input,
eligible_connectors,
profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
}
pub async fn perform_fallback_routing(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
#[cfg(feature = "v1")]
let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?
.get_string_repr(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => {
payout_data.payout_attempt.profile_id.get_string_repr()
}
},
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
#[cfg(feature = "v2")]
let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
fallback_config,
backend_input,
eligible_connectors,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await
}
pub async fn perform_eligibility_analysis_with_fallback(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
logger::debug!("euclid_routing: performing eligibility");
let mut final_selection = perform_eligibility_analysis(
state,
key_store,
chosen,
transaction_data,
eligible_connectors.as_ref(),
business_profile.get_id(),
)
.await?;
let fallback_selection = perform_fallback_routing(
state,
key_store,
transaction_data,
eligible_connectors.as_ref(),
business_profile,
)
.await;
final_selection.append(
&mut fallback_selection
.unwrap_or_default()
.iter()
.filter(|&routable_connector_choice| {
!final_selection.contains(routable_connector_choice)
})
.cloned()
.collect::<Vec<_>>(),
);
let final_selected_connectors = final_selection
.iter()
.map(|item| item.connector)
.collect::<Vec<_>>();
logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "euclid_routing: List of final selected connectors for routing");
Ok(final_selection)
}
#[cfg(feature = "v2")]
pub async fn perform_session_flow_routing<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>>
{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = business_profile.get_id().clone();
let routing_algorithm =
MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone());
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input
.payment_intent
.amount_details
.calculate_net_amount(),
currency: session_input.payment_intent.amount_details.currency,
authentication_type: session_input.payment_intent.authentication_type,
card_bin: None,
capture_method: Option::<euclid_enums::CaptureMethod>::foreign_from(
session_input.payment_intent.capture_method,
),
// business_country not available in payment_intent anymore
business_country: None,
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
// business_label not available in payment_intent anymore
business_label: None,
setup_future_usage: Some(session_input.payment_intent.setup_future_usage),
};
let metadata = session_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let routable_connector_choice_option = perform_session_routing_for_pm_type(
state,
key_store,
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok(result)
}
#[cfg(feature = "v1")]
pub async fn perform_session_flow_routing(
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<(
FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>,
Option<common_enums::RoutingApproach>,
)> {
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = session_input
.payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
.transpose()
.change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)?
.unwrap_or_default()
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input.payment_attempt.get_total_amount(),
currency: session_input
.payment_intent
.currency
.get_required_value("Currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: session_input.payment_attempt.authentication_type,
card_bin: None,
capture_method: session_input
.payment_attempt
.capture_method
.and_then(Option::<euclid_enums::CaptureMethod>::foreign_from),
business_country: session_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
business_label: session_input.payment_intent.business_label.clone(),
setup_future_usage: session_input.payment_intent.setup_future_usage,
};
let metadata = session_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
let mut final_routing_approach = None;
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
state: session_input.state,
key_store: session_input.key_store,
attempt_id: session_input.payment_attempt.get_id(),
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let (routable_connector_choice_option, routing_approach) =
perform_session_routing_for_pm_type(
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
final_routing_approach = routing_approach;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&session_pm_input.state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok((result, final_routing_approach))
}
#[cfg(feature = "v1")]
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<(
Option<Vec<api_models::routing::RoutableConnectorChoice>>,
Option<common_enums::RoutingApproach>,
)> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let (chosen_connectors, routing_approach) = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => (
vec![(**conn).clone()],
Some(common_enums::RoutingApproach::StraightThroughRouting),
),
CachedAlgorithm::Priority(plist) => (plist.clone(), None),
CachedAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
Some(common_enums::RoutingApproach::VolumeBasedRouting),
),
CachedAlgorithm::Advanced(interpreter) => (
execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
Some(common_enums::RoutingApproach::RuleBasedRouting),
),
}
} else {
(
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?,
None,
)
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok((None, routing_approach))
} else {
Ok((Some(final_selection), routing_approach))
}
}
#[cfg(feature = "v2")]
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
CachedAlgorithm::Priority(plist) => plist.clone(),
CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
#[cfg(feature = "v2")]
async fn perform_session_routing_for_pm_type<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
let chosen_connectors = get_chosen_connectors(
state,
key_store,
session_pm_input,
transaction_type,
&profile_wrapper,
)
.await?;
let mut final_selection = perform_cgraph_filtering(
state,
key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
state,
key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok(None)
} else {
Ok(Some(final_selection))
}
}
#[cfg(feature = "v2")]
pub fn make_dsl_input_for_surcharge(
_payment_attempt: &oss_storage::PaymentAttempt,
_payment_intent: &oss_storage::PaymentIntent,
_billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
todo!()
}
#[cfg(feature = "v1")]
pub fn make_dsl_input_for_surcharge(
payment_attempt: &oss_storage::PaymentAttempt,
payment_intent: &oss_storage::PaymentIntent,
billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: payment_attempt.get_total_amount(),
// currency is always populated in payment_attempt during payment create
currency: payment_attempt
.currency
.get_required_value("currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: payment_attempt.authentication_type,
card_bin: None,
capture_method: payment_attempt.capture_method,
business_country: payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: billing_address
.and_then(|bic| bic.address)
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payment_intent.business_label.clone(),
setup_future_usage: payment_intent.setup_future_usage,
};
let metadata = payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
Ok(backend_input)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_open_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
payment_data: oss_storage::PaymentAttempt,
old_payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing with open_router for profile {}",
profile.get_id().get_string_repr()
);
let is_success_rate_routing_enabled =
dynamic_routing_algo_ref.is_success_rate_routing_enabled();
let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();
// Since success_based and elimination routing is being done in 1 api call, we call decide_gateway when either of it enabled
let connectors = if is_success_rate_routing_enabled || is_elimination_enabled {
let connectors = perform_decide_gateway_call_with_open_router(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_data,
is_elimination_enabled,
old_payment_data,
)
.await?;
if is_elimination_enabled {
// This will initiate the elimination process for the connector.
// Penalize the elimination score of the connector before making a payment.
// Once the payment is made, we will update the score based on the payment status
if let Some(connector) = connectors.first() {
logger::debug!(
"penalizing the elimination score of the gateway with id {} in open_router for profile {}",
connector, profile.get_id().get_string_repr()
);
update_gateway_score_with_open_router(
state,
connector.clone(),
profile.get_id(),
&payment_data.merchant_id,
&payment_data.payment_id,
common_enums::AttemptStatus::AuthenticationPending,
)
.await?
}
}
connectors
} else {
routable_connectors
};
Ok(connectors)
}
#[cfg(feature = "v1")]
pub async fn perform_open_routing_for_debit_routing<F, D>(
state: &SessionState,
co_badged_card_request: or_types::CoBadgedCardRequest,
card_isin: Option<Secret<String>>,
old_payment_data: &mut D,
) -> RoutingResult<or_types::DebitRoutingOutput>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let payment_attempt = old_payment_data.get_payment_attempt().clone();
logger::debug!(
"performing debit routing with open_router for profile {}",
payment_attempt.profile_id.get_string_repr()
);
let metadata = Some(
serde_json::to_string(&co_badged_card_request)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode Vaulting data to string")
.change_context(errors::RoutingError::MetadataParsingError)?,
);
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request(
&payment_attempt,
metadata,
card_isin,
Some(or_types::RankingAlgorithm::NtwBasedRouting),
);
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"DecisionEngine: Debit Routing".to_string(),
Some(open_router_req_body.clone()),
true,
true,
);
let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> =
utils::EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"decide-gateway",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
let output = match response {
Ok(events_response) => {
let response =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
let debit_routing_output = response
.debit_routing_output
.get_required_value("debit_routing_output")
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))
.attach_printable("debit_routing_output is missing in the open routing response")?;
old_payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::from_decision_engine_approach(
&response.routing_approach,
),
));
Ok(debit_routing_output)
}
Err(error_response) => {
logger::error!("open_router_error_response: {:?}", error_response);
Err(errors::RoutingError::OpenRouterError(
"Failed to perform debit routing in open router".into(),
))
}
}?;
Ok(output)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_intelligent_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing for profile {}",
profile.get_id().get_string_repr()
);
let payment_attempt = payment_data.get_payment_attempt().clone();
let mut connector_list = match dynamic_routing_algo_ref
.success_based_algorithm
.as_ref()
.async_map(|algorithm| {
perform_success_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
{
Some(success_based_list) => success_based_list,
None => {
// Only run contract based if success based returns None
dynamic_routing_algo_ref
.contract_based_routing
.as_ref()
.async_map(|algorithm| {
perform_contract_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(routable_connectors.clone())
}
};
connector_list = dynamic_routing_algo_ref
.elimination_routing_algorithm
.as_ref()
.async_map(|algorithm| {
perform_elimination_routing(
state,
connector_list.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(connector_list);
Ok(connector_list)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn perform_decide_gateway_call_with_open_router<F, D>(
state: &SessionState,
mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
payment_attempt: &oss_storage::PaymentAttempt,
is_elimination_enabled: bool,
old_payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
logger::debug!(
"performing decide_gateway call with open_router for profile {}",
profile_id.get_string_repr()
);
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request(
payment_attempt,
routable_connectors.clone(),
Some(or_types::RankingAlgorithm::SrBasedRouting),
is_elimination_enabled,
);
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"DecisionEngine: SuccessRate decide_gateway".to_string(),
Some(open_router_req_body.clone()),
true,
false,
);
let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> =
utils::SRApiClient::send_decision_engine_request(
state,
services::Method::Post,
"decide-gateway",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
let sr_sorted_connectors = match response {
Ok(resp) => {
let decided_gateway: DecidedGateway =
resp.response.ok_or(errors::RoutingError::OpenRouterError(
"Empty response received from open_router".into(),
))?;
let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError {
message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_response_body(&decided_gateway);
routing_event.set_routing_approach(
utils::RoutingApproach::from_decision_engine_approach(
&decided_gateway.routing_approach,
)
.to_string(),
);
old_payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::from_decision_engine_approach(
&decided_gateway.routing_approach,
),
));
if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map {
logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response");
routable_connectors.sort_by(|connector_choice_a, connector_choice_b| {
let connector_choice_a_score = gateway_priority_map
.get(&connector_choice_a.to_string())
.copied()
.unwrap_or(0.0);
let connector_choice_b_score = gateway_priority_map
.get(&connector_choice_b.to_string())
.copied()
.unwrap_or(0.0);
connector_choice_b_score
.partial_cmp(&connector_choice_a_score)
.unwrap_or(std::cmp::Ordering::Equal)
});
}
routing_event.set_routable_connectors(routable_connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(routable_connectors)
}
Err(err) => {
logger::error!("open_router_error_response: {:?}", err);
Err(errors::RoutingError::OpenRouterError(
"Failed to perform decide_gateway call in open_router".into(),
))
}
}?;
Ok(sr_sorted_connectors)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_gateway_score_with_open_router(
state: &SessionState,
payment_connector: api_routing::RoutableConnectorChoice,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
payment_status: common_enums::AttemptStatus,
) -> RoutingResult<()> {
let open_router_req_body = or_types::UpdateScorePayload {
merchant_id: profile_id.clone(),
gateway: payment_connector.to_string(),
status: payment_status.foreign_into(),
payment_id: payment_id.clone(),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"DecisionEngine: SuccessRate update_gateway_score".to_string(),
Some(open_router_req_body.clone()),
true,
false,
);
let response: RoutingResult<utils::RoutingEventsResponse<or_types::UpdateScoreResponse>> =
utils::SRApiClient::send_decision_engine_request(
state,
services::Method::Post,
"update-gateway-score",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
match response {
Ok(resp) => {
let update_score_resp = resp.response.ok_or(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError {
message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
logger::debug!(
"open_router update_gateway_score response for gateway with id {}: {:?}",
payment_connector,
update_score_resp.message
);
routing_event.set_response_body(&update_score_resp);
routing_event.set_payment_connector(payment_connector.clone()); // check this in review
state.event_handler().log_event(&routing_event);
Ok(())
}
Err(err) => {
logger::error!("open_router_update_gateway_score_error: {:?}", err);
Err(errors::RoutingError::OpenRouterError(
"Failed to update gateway score in open_router".into(),
))
}
}?;
Ok(())
}
/// success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn perform_success_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
success_based_algo_ref: api_routing::SuccessBasedAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if success_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing success_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::SuccessRateClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.success_rate_client;
let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "success_based_routing_algorithm_id".to_string(),
})
.attach_printable("success_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
.attach_printable("unable to fetch success_rate based dynamic routing configs")?;
let success_based_routing_config_params = success_based_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?,
);
let event_request = utils::CalSuccessRateEventRequest {
id: profile_id.get_string_repr().to_string(),
params: success_based_routing_config_params.clone(),
labels: routable_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: success_based_routing_configs
.config
.as_ref()
.map(utils::CalSuccessRateConfigEventRequest::from),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: CalculateSuccessRate".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let success_based_connectors_result = client
.calculate_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
routable_connectors,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::SuccessRateCalculationError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
);
match success_based_connectors_result {
Ok(success_response) => {
let updated_resp = utils::CalSuccessRateEventResponse::try_from(
&success_response,
)
.change_context(errors::RoutingError::RoutingEventsError { message: "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse".to_string(), status_code: 500 })
.attach_printable(
"unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse",
)?;
Ok(Some(updated_resp))
}
Err(e) => {
logger::error!(
"unable to calculate/fetch success rate from dynamic routing service: {:?}",
e.current_context()
);
Err(error_stack::report!(
errors::RoutingError::SuccessRateCalculationError
))
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"SuccessRateCalculator.FetchSuccessRate".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let success_based_connectors: utils::CalSuccessRateEventResponse = events_response
.response
.ok_or(errors::RoutingError::SuccessRateCalculationError)?;
// Need to log error case
let mut routing_event =
events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(success_based_connectors.routing_approach.to_string());
payment_data.set_routing_approach_in_attempt(Some(common_enums::RoutingApproach::from(
success_based_connectors.routing_approach,
)));
let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len());
for label_with_score in success_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
logger::debug!(success_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
/// elimination dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_elimination_routing(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
elimination_routing_configs_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
elimination_algo_ref: api_routing::EliminationRoutingAlgorithm,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
if elimination_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing elimination_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::EliminationClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.elimination_based_client;
let elimination_routing_config = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::EliminationRoutingConfig,
>(
state,
profile_id,
elimination_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "elimination_routing_algorithm_id".to_string(),
})
.attach_printable(
"elimination_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::RoutingError::EliminationRoutingConfigError)
.attach_printable("unable to fetch elimination dynamic routing configs")?;
let elimination_routing_config_params = elimination_routing_configs_params_interpolator
.get_string_val(
elimination_routing_config
.params
.as_ref()
.ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?,
);
let event_request = utils::EliminationRoutingEventRequest {
id: profile_id.get_string_repr().to_string(),
params: elimination_routing_config_params.clone(),
labels: routable_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: elimination_routing_config
.elimination_analyser_config
.as_ref()
.map(utils::EliminationRoutingEventBucketConfig::from),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformEliminationRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let elimination_based_connectors_result = client
.perform_elimination_routing(
profile_id.get_string_repr().to_string(),
elimination_routing_config_params,
routable_connectors.clone(),
elimination_routing_config.elimination_analyser_config,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::EliminationRoutingCalculationError)
.attach_printable(
"unable to analyze/fetch elimination routing from dynamic routing service",
);
match elimination_based_connectors_result {
Ok(elimination_response) => Ok(Some(utils::EliminationEventResponse::from(
&elimination_response,
))),
Err(e) => {
logger::error!(
"unable to analyze/fetch elimination routing from dynamic routing service: {:?}",
e.current_context()
);
Err(error_stack::report!(
errors::RoutingError::EliminationRoutingCalculationError
))
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"EliminationAnalyser.GetEliminationStatus".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let elimination_based_connectors: utils::EliminationEventResponse = events_response
.response
.ok_or(errors::RoutingError::EliminationRoutingCalculationError)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(utils::RoutingApproach::Elimination.to_string());
let mut connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
let mut eliminated_connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
let mut non_eliminated_connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
for labels_with_status in elimination_based_connectors.labels_with_status {
let (connector, merchant_connector_id) = labels_with_status.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidEliminationBasedConnectorLabel(labels_with_status.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the elimination based dynamic routing service",
)?;
let routable_connector = api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
};
if labels_with_status
.elimination_information
.is_some_and(|elimination_info| {
elimination_info
.entity
.is_some_and(|entity_info| entity_info.is_eliminated)
})
{
eliminated_connectors.push(routable_connector);
} else {
non_eliminated_connectors.push(routable_connector);
}
connectors.extend(non_eliminated_connectors.clone());
connectors.extend(eliminated_connectors.clone());
}
logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors);
logger::debug!(dynamic_elimination_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[allow(clippy::too_many_arguments)]
pub async fn perform_contract_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
_dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if contract_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing contract_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::ContractRoutingClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.contract_based_client;
let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::ContractBasedRoutingConfig,
>(
state,
profile_id,
contract_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "contract_based_routing_algorithm_id".to_string(),
})
.attach_printable("contract_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("unable to fetch contract based dynamic routing configs")?;
let label_info = contract_based_routing_configs
.label_info
.clone()
.ok_or(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("Label information not found in contract routing configs")?;
let contract_based_connectors = routable_connectors
.clone()
.into_iter()
.filter(|conn| {
label_info
.iter()
.any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let mut other_connectors = routable_connectors
.into_iter()
.filter(|conn| {
label_info
.iter()
.all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let event_request = utils::CalContractScoreEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels: contract_based_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: Some(contract_based_routing_configs.clone()),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformContractRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let contract_based_connectors_result = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_configs.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.attach_printable(
"unable to calculate/fetch contract score from dynamic routing service",
);
let contract_based_connectors = match contract_based_connectors_result {
Ok(resp) => Some(utils::CalContractScoreEventResponse::from(&resp)),
Err(err) => match err.current_context() {
DynamicRoutingError::ContractNotFound => {
client
.update_contracts(
profile_id.get_string_repr().into(),
label_info,
"".to_string(),
vec![],
u64::default(),
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::ContractScoreUpdationError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
)?;
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into());
}
_ => {
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into())
}
},
};
Ok(contract_based_connectors)
};
let events_response = routing_events_wrapper
.construct_event_builder(
"ContractScoreCalculator.FetchContractScore".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let contract_based_connectors: utils::CalContractScoreEventResponse = events_response
.response
.ok_or(errors::RoutingError::ContractScoreCalculationError {
err: "CalContractScoreEventResponse not found".to_string(),
})?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::ContractBasedRouting,
));
let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());
for label_with_score in contract_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
connectors.append(&mut other_connectors);
logger::debug!(contract_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
routing_event.set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/routing.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_2235041506038621469 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/utils/refunds_validator.rs
// Contains: 0 structs, 1 enums
use diesel_models::refund as diesel_refund;
use error_stack::report;
use router_env::{instrument, tracing};
use time::PrimitiveDateTime;
use crate::{
core::errors::{self, CustomResult, RouterResult},
types::{
self,
api::enums as api_enums,
storage::{self, enums},
},
utils::{self, OptionExt},
};
// Limit constraints for refunds list flow
pub const LOWER_LIMIT: i64 = 1;
pub const UPPER_LIMIT: i64 = 100;
pub const DEFAULT_LIMIT: i64 = 10;
#[derive(Debug, thiserror::Error)]
pub enum RefundValidationError {
#[error("The payment attempt was not successful")]
UnsuccessfulPaymentAttempt,
#[error("The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error("The order has expired")]
OrderExpired,
#[error("The maximum refund count for this payment attempt")]
MaxRefundCountReached,
#[error("There is already another refund request for this payment attempt")]
DuplicateRefund,
}
#[instrument(skip_all)]
pub fn validate_success_transaction(
transaction: &storage::PaymentAttempt,
) -> CustomResult<(), RefundValidationError> {
if transaction.status != enums::AttemptStatus::Charged {
Err(report!(RefundValidationError::UnsuccessfulPaymentAttempt))?
}
Ok(())
}
#[instrument(skip_all)]
pub fn validate_refund_amount(
amount_captured: i64,
all_refunds: &[diesel_refund::Refund],
refund_amount: i64,
) -> CustomResult<(), RefundValidationError> {
let total_refunded_amount: i64 = all_refunds
.iter()
.filter_map(|refund| {
if refund.refund_status != enums::RefundStatus::Failure
&& refund.refund_status != enums::RefundStatus::TransactionFailure
{
Some(refund.refund_amount.get_amount_as_i64())
} else {
None
}
})
.sum();
utils::when(
refund_amount > (amount_captured - total_refunded_amount),
|| {
Err(report!(
RefundValidationError::RefundAmountExceedsPaymentAmount
))
},
)
}
#[instrument(skip_all)]
pub fn validate_payment_order_age(
created_at: &PrimitiveDateTime,
refund_max_age: i64,
) -> CustomResult<(), RefundValidationError> {
let current_time = common_utils::date_time::now();
utils::when(
(current_time - *created_at).whole_days() > refund_max_age,
|| Err(report!(RefundValidationError::OrderExpired)),
)
}
#[instrument(skip_all)]
pub fn validate_maximum_refund_against_payment_attempt(
all_refunds: &[diesel_refund::Refund],
refund_max_attempts: usize,
) -> CustomResult<(), RefundValidationError> {
utils::when(all_refunds.len() > refund_max_attempts, || {
Err(report!(RefundValidationError::MaxRefundCountReached))
})
}
pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::ApiErrorResponse> {
match limit {
Some(limit_val) => {
if !(LOWER_LIMIT..=UPPER_LIMIT).contains(&limit_val) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "limit should be in between 1 and 100".to_string(),
}
.into())
} else {
Ok(limit_val)
}
}
None => Ok(DEFAULT_LIMIT),
}
}
#[cfg(feature = "v1")]
pub fn validate_for_valid_refunds(
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector: api_models::enums::Connector,
) -> RouterResult<()> {
let payment_method = payment_attempt
.payment_method
.as_ref()
.get_required_value("payment_method")?;
match payment_method {
diesel_models::enums::PaymentMethod::PayLater
| diesel_models::enums::PaymentMethod::Wallet => {
let payment_method_type = payment_attempt
.payment_method_type
.get_required_value("payment_method_type")?;
utils::when(
matches!(
(connector, payment_method_type),
(
api_models::enums::Connector::Braintree,
diesel_models::enums::PaymentMethodType::Paypal,
)
),
|| {
Err(errors::ApiErrorResponse::RefundNotPossible {
connector: connector.to_string(),
}
.into())
},
)
}
_ => Ok(()),
}
}
#[cfg(feature = "v2")]
pub fn validate_for_valid_refunds(
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector: api_models::enums::Connector,
) -> RouterResult<()> {
let payment_method_type = payment_attempt.payment_method_type;
match payment_method_type {
diesel_models::enums::PaymentMethod::PayLater
| diesel_models::enums::PaymentMethod::Wallet => {
let payment_method_subtype = payment_attempt.payment_method_subtype;
utils::when(
matches!(
(connector, payment_method_subtype),
(
api_models::enums::Connector::Braintree,
diesel_models::enums::PaymentMethodType::Paypal,
)
),
|| {
Err(errors::ApiErrorResponse::RefundNotPossible {
connector: connector.to_string(),
}
.into())
},
)
}
_ => Ok(()),
}
}
pub fn validate_stripe_charge_refund(
charge_type_option: Option<api_enums::PaymentChargeType>,
split_refund_request: &Option<common_types::refunds::SplitRefund>,
) -> RouterResult<types::ChargeRefundsOptions> {
let charge_type = charge_type_option.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing `charge_type` in PaymentAttempt.")
})?;
let refund_request = match split_refund_request {
Some(common_types::refunds::SplitRefund::StripeSplitRefund(stripe_split_refund)) => {
stripe_split_refund
}
_ => Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "stripe_split_refund",
})?,
};
let options = match charge_type {
api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => {
types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {
revert_platform_fee: refund_request
.revert_platform_fee
.get_required_value("revert_platform_fee")?,
})
}
api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => {
types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund {
revert_platform_fee: refund_request
.revert_platform_fee
.get_required_value("revert_platform_fee")?,
revert_transfer: refund_request
.revert_transfer
.get_required_value("revert_transfer")?,
})
}
};
Ok(options)
}
pub fn validate_adyen_charge_refund(
adyen_split_payment_response: &common_types::domain::AdyenSplitData,
adyen_split_refund_request: &common_types::domain::AdyenSplitData,
) -> RouterResult<()> {
if adyen_split_refund_request.store != adyen_split_payment_response.store {
return Err(report!(errors::ApiErrorResponse::InvalidDataValue {
field_name: "split_payments.adyen_split_payment.store",
}));
};
for refund_split_item in adyen_split_refund_request.split_items.iter() {
let refund_split_reference = refund_split_item.reference.clone();
let matching_payment_split_item = adyen_split_payment_response
.split_items
.iter()
.find(|payment_split_item| refund_split_reference == payment_split_item.reference);
if let Some(payment_split_item) = matching_payment_split_item {
if let Some((refund_amount, payment_amount)) =
refund_split_item.amount.zip(payment_split_item.amount)
{
if refund_amount > payment_amount {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid refund amount for split item, reference: {refund_split_reference}",
),
}));
}
}
if let Some((refund_account, payment_account)) = refund_split_item
.account
.as_ref()
.zip(payment_split_item.account.as_ref())
{
if !refund_account.eq(payment_account) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid refund account for split item, reference: {refund_split_reference}",
),
}));
}
}
if refund_split_item.split_type != payment_split_item.split_type {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid refund split_type for split item, reference: {refund_split_reference}",
),
}));
}
} else {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"No matching payment split item found for reference: {refund_split_reference}",
),
}));
}
}
Ok(())
}
pub fn validate_xendit_charge_refund(
xendit_split_payment_response: &common_types::payments::XenditChargeResponseData,
xendit_split_refund_request: &common_types::domain::XenditSplitSubMerchantData,
) -> RouterResult<Option<String>> {
match xendit_split_payment_response {
common_types::payments::XenditChargeResponseData::MultipleSplits(
payment_sub_merchant_data,
) => {
if payment_sub_merchant_data.for_user_id
!= Some(xendit_split_refund_request.for_user_id.clone())
{
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "xendit_split_refund.for_user_id does not match xendit_split_payment.for_user_id",
}.into());
}
Ok(Some(xendit_split_refund_request.for_user_id.clone()))
}
common_types::payments::XenditChargeResponseData::SingleSplit(
payment_sub_merchant_data,
) => {
if payment_sub_merchant_data.for_user_id != xendit_split_refund_request.for_user_id {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "xendit_split_refund.for_user_id does not match xendit_split_payment.for_user_id",
}.into());
}
Ok(Some(xendit_split_refund_request.for_user_id.clone()))
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/utils/refunds_validator.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-6957101065590432410 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/revenue_recovery/types.rs
// Contains: 0 structs, 2 enums
use std::{marker::PhantomData, str::FromStr};
use api_models::{
enums as api_enums,
payments::{
AmountDetails, PaymentRevenueRecoveryMetadata, PaymentsUpdateIntentRequest,
ProxyPaymentsRequest,
},
};
use common_utils::{
self,
ext_traits::{OptionExt, ValueExt},
id_type,
};
use diesel_models::{
enums, payment_intent, process_tracker::business_status, types as diesel_types,
};
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
api::ApplicationResponse,
business_profile, merchant_connector_account,
merchant_context::{Context, MerchantContext},
payments::{
self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData,
PaymentIntent, PaymentIntentData, PaymentStatusData,
},
router_data_v2::{self, flow_common_types},
router_flow_types,
router_request_types::revenue_recovery as revenue_recovery_request,
router_response_types::revenue_recovery as revenue_recovery_response,
ApiModelToDieselModelConvertor,
};
use time::PrimitiveDateTime;
use super::errors::StorageErrorExt;
use crate::{
core::{
errors::{self, RouterResult},
payments::{self, helpers, operations::Operation, transformers::GenerateResponse},
revenue_recovery::{self as revenue_recovery_core, pcr, perform_calculate_workflow},
webhooks::{
create_event_and_trigger_outgoing_webhook, recovery_incoming as recovery_incoming_flow,
},
},
db::StorageInterface,
logger,
routes::SessionState,
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self, api as api_types, api::payments as payments_types, domain, storage,
transformers::ForeignInto,
},
workflows::{
payment_sync,
revenue_recovery::{self, get_schedule_time_to_retry_mit_payments},
},
};
type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>;
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
/// The status of Passive Churn Payments
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum RevenueRecoveryPaymentsAttemptStatus {
Succeeded,
Failed,
Processing,
InvalidStatus(String),
// Cancelled,
}
impl RevenueRecoveryPaymentsAttemptStatus {
pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment(
&self,
db: &dyn StorageInterface,
execute_task_process: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering update_pt_status_based_on_attempt_status_for_execute_payment");
match &self {
Self::Succeeded | Self::Failed | Self::Processing => {
// finish the current execute task
db.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await?;
}
Self::InvalidStatus(action) => {
logger::debug!(
"Invalid Attempt Status for the Recovery Payment : {}",
action
);
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.update_process(execute_task_process.clone(), pt_update)
.await?;
}
};
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn update_pt_status_based_on_attempt_status_for_payments_sync(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
process_tracker: storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_attempt: PaymentAttempt,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
) -> Result<(), errors::ProcessTrackerError> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let db = &*state.store;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_attempt,
);
let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt);
let retry_count = process_tracker.retry_count;
let psync_response = revenue_recovery_payment_data
.psync_data
.as_ref()
.ok_or(errors::RecoveryError::ValueNotFound)
.attach_printable("Psync data not found in revenue recovery payment data")?;
match self {
Self::Succeeded => {
// finish psync task as the payment was a success
db.as_scheduler()
.finish_process_with_business_status(
process_tracker,
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await?;
let event_status = common_enums::EventType::PaymentSucceeded;
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
// Since this is succeeded payment attempt, 'is_hard_decine' will be false.
&Some(false),
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
let payments_response = psync_response
.clone()
.generate_response(state, None, None, None, &merchant_context, profile, None)
.change_context(errors::RecoveryError::PaymentsResponseGenerationFailed)
.attach_printable("Failed while generating response for payment")?;
RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_status,
payment_intent,
&merchant_context,
profile,
recovery_payment_attempt
.attempt_id
.get_string_repr()
.to_string(),
payments_response
)
.await?;
// Record a successful transaction back to Billing Connector
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
&payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
}
Self::Failed => {
// finish psync task
db.as_scheduler()
.finish_process_with_business_status(
process_tracker.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await?;
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}", e
);
};
let error_code = recovery_payment_attempt.error_code;
let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
&process_tracker,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
psync_response.payment_attempt.get_id(),
))
.await?;
}
Self::Processing => {
// do a psync payment
let action = Box::pin(Action::payment_sync_call(
state,
revenue_recovery_payment_data,
payment_intent,
&process_tracker,
profile,
merchant_context,
payment_attempt,
))
.await?;
//handle the response
Box::pin(action.psync_response_handler(
state,
payment_intent,
&process_tracker,
revenue_recovery_metadata,
revenue_recovery_payment_data,
))
.await?;
}
Self::InvalidStatus(status) => logger::debug!(
"Invalid Attempt Status for the Recovery Payment : {}",
status
),
}
Ok(())
}
}
pub enum Decision {
Execute,
Psync(enums::AttemptStatus, id_type::GlobalAttemptId),
InvalidDecision,
ReviewForSuccessfulPayment,
ReviewForFailedPayment(enums::TriggeredBy),
}
impl Decision {
pub async fn get_decision_based_on_params(
state: &SessionState,
intent_status: enums::IntentStatus,
called_connector: enums::PaymentConnectorTransmission,
active_attempt_id: Option<id_type::GlobalAttemptId>,
revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_id: &id_type::GlobalPaymentId,
) -> RecoveryResult<Self> {
logger::info!("Entering get_decision_based_on_params");
Ok(match (intent_status, called_connector, active_attempt_id) {
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
None,
) => Self::Execute,
(
enums::IntentStatus::Processing,
enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
Some(_),
) => {
let psync_data = revenue_recovery_core::api::call_psync_api(
state,
payment_id,
revenue_recovery_data,
true,
true,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data.payment_attempt;
Self::Psync(payment_attempt.status, payment_attempt.get_id().clone())
}
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
Some(_),
) => {
let psync_data = revenue_recovery_core::api::call_psync_api(
state,
payment_id,
revenue_recovery_data,
true,
true,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data.payment_attempt;
let attempt_triggered_by = payment_attempt
.feature_metadata
.and_then(|metadata| {
metadata.revenue_recovery.map(|revenue_recovery_metadata| {
revenue_recovery_metadata.attempt_triggered_by
})
})
.get_required_value("Attempt Triggered By")
.change_context(errors::RecoveryError::ValueNotFound)?;
Self::ReviewForFailedPayment(attempt_triggered_by)
}
(enums::IntentStatus::Succeeded, _, _) => Self::ReviewForSuccessfulPayment,
_ => Self::InvalidDecision,
})
}
}
#[derive(Debug, Clone)]
pub enum Action {
SyncPayment(PaymentAttempt),
RetryPayment(PrimitiveDateTime),
TerminalFailure(PaymentAttempt),
SuccessfulPayment(PaymentAttempt),
ReviewPayment,
ManualReviewAction,
}
impl Action {
#[allow(clippy::too_many_arguments)]
pub async fn execute_payment(
state: &SessionState,
_merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<Self> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let last_token_used = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.payment_processor_token
.clone()
});
let recovery_algorithm = tracking_data.revenue_recovery_retry;
let scheduled_token = match storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(
state,
&connector_customer_id,
recovery_algorithm,
last_token_used.as_deref(),
)
.await {
Ok(scheduled_token_opt) => scheduled_token_opt,
Err(e) => {
logger::error!(
error = ?e,
connector_customer_id = %connector_customer_id,
"Failed to get PSP token status"
);
None
}
};
match scheduled_token {
Some(scheduled_token) => {
let response = revenue_recovery_core::api::call_proxy_api(
state,
payment_intent,
revenue_recovery_payment_data,
revenue_recovery_metadata,
&scheduled_token
.payment_processor_token_details
.payment_processor_token,
)
.await;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
// handle proxy api's response
match response {
Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
&is_hard_decline,
Some(&scheduled_token.payment_processor_token_details.payment_processor_token),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
let event_status = common_enums::EventType::PaymentSucceeded;
let payments_response = payment_data
.clone()
.generate_response(
state,
None,
None,
None,
&merchant_context,
profile,
None,
)
.change_context(
errors::RecoveryError::PaymentsResponseGenerationFailed,
)
.attach_printable("Failed while generating response for payment")?;
RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_status,
payment_intent,
&merchant_context,
profile,
payment_data.payment_attempt.id.get_string_repr().to_string(),
payments_response
)
.await?;
Ok(Self::SuccessfulPayment(
payment_data.payment_attempt.clone(),
))
}
RevenueRecoveryPaymentsAttemptStatus::Failed => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let error_code = payment_data
.payment_attempt
.clone()
.error
.map(|error| error.code);
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
Some(&scheduled_token
.payment_processor_token_details
.payment_processor_token)
,
)
.await;
// unlocking the token
let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
process,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
latest_attempt_id,
))
.await?;
// Return terminal failure to finish the current execute workflow
Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// check for an active attempt being constructed or not
{
logger::error!(execute_payment_res=?err);
Ok(Self::ReviewPayment)
}
}
}
None => {
let response = revenue_recovery_core::api::call_psync_api(
state,
payment_intent.get_id(),
revenue_recovery_payment_data,
true,
true,
)
.await;
let payment_status_data = response
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = payment_status_data.payment_attempt;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token available, finishing CALCULATE_WORKFLOW"
);
state
.store
.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::CALCULATE_WORKFLOW_FINISH,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to finish CALCULATE_WORKFLOW")?;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"CALCULATE_WORKFLOW finished successfully"
);
Ok(Self::TerminalFailure(payment_attempt.clone()))
}
}
}
pub async fn execute_payment_task_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
execute_task_process: &storage::ProcessTracker,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering execute_payment_task_response_handler");
let db = &*state.store;
match self {
Self::SyncPayment(payment_attempt) => {
revenue_recovery_core::insert_psync_pcr_task_to_pt(
revenue_recovery_payment_data.billing_mca.get_id().clone(),
db,
revenue_recovery_payment_data
.merchant_account
.get_id()
.to_owned(),
payment_intent.id.clone(),
revenue_recovery_payment_data.profile.get_id().to_owned(),
payment_attempt.id.clone(),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
revenue_recovery_payment_data.retry_algorithm,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to create a psync workflow in the process tracker")?;
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
db.as_scheduler()
.retry_process(execute_task_process.clone(), *schedule_time)
.await?;
// update the connector payment transmission field to Unsuccessful and unset active attempt id
revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
);
let payment_update_req =
PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
payment_intent
.feature_metadata
.clone()
.unwrap_or_default()
.convert_back()
.set_payment_revenue_recovery_metadata_using_api(
revenue_recovery_metadata.clone(),
),
api_enums::UpdateActiveAttempt::Unset,
);
logger::info!(
"Call made to payments update intent api , with the request body {:?}",
payment_update_req
);
revenue_recovery_core::api::update_payment_intent_api(
state,
payment_intent.id.clone(),
revenue_recovery_payment_data,
payment_update_req,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_FAILURE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// TODO: Add support for retrying failed outgoing recordback webhooks
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record back to billing connector for terminal status
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => {
// requeue the process tracker in case of error response
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
}
}
pub async fn payment_sync_call(
state: &SessionState,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_attempt: PaymentAttempt,
) -> RecoveryResult<Self> {
logger::info!("Entering payment_sync_call");
let response = revenue_recovery_core::api::call_psync_api(
state,
payment_intent.get_id(),
revenue_recovery_payment_data,
true,
true,
)
.await;
let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt);
match response {
Ok(_payment_data) => match payment_attempt.status.foreign_into() {
RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
// Since this is succeeded, 'hard_decine' will be false.
&Some(false),
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
Ok(Self::SuccessfulPayment(payment_attempt))
}
RevenueRecoveryPaymentsAttemptStatus::Failed => {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let error_code = payment_attempt.clone().error.map(|error| error.code);
let is_hard_decline =
revenue_recovery::check_hard_decline(state, &payment_attempt)
.await
.ok();
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
process,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
payment_attempt.get_id(),
))
.await?;
Ok(Self::TerminalFailure(payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_attempt))
}
RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR PSync Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// if there is an error while psync we create a new Review Task
{
logger::error!(sync_payment_response=?err);
Ok(Self::ReviewPayment)
}
}
}
pub async fn psync_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
psync_task_process: &storage::ProcessTracker,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering psync_response_handler");
let db = &*state.store;
let connector_customer_id = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.connector_customer_id
.clone()
});
match self {
Self::SyncPayment(payment_attempt) => {
// get a schedule time for psync
// and retry the process if there is a schedule time
// if None mark the pt status as Retries Exceeded and finish the task
payment_sync::recovery_retry_sync_task(
state,
connector_customer_id,
revenue_recovery_metadata.connector.to_string(),
revenue_recovery_payment_data
.merchant_account
.get_id()
.clone(),
psync_task_process.clone(),
)
.await?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
// finish the psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// fetch the execute task
let task = revenue_recovery_core::EXECUTE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = payment_intent
.get_id()
.get_execute_revenue_recovery_id(task, runner);
let execute_task_process = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)?
.get_required_value("Process Tracker")?;
// retry the execute tasks
db.as_scheduler()
.retry_process(execute_task_process, *schedule_time)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
// TODO: Add support for retrying failed outgoing recordback webhooks
// finish the current psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
// finish the current psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record a successful transaction back to Billing Connector
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => {
// requeue the process tracker task in case of psync api error
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::PSYNC_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(psync_task_process.clone(), pt_update)
.await?;
Ok(())
}
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::PSYNC_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(psync_task_process.clone(), pt_update)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
}
}
pub(crate) async fn decide_retry_failure_action(
state: &SessionState,
merchant_id: &id_type::MerchantId,
pt: storage::ProcessTracker,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> RecoveryResult<Self> {
let db = &*state.store;
let next_retry_count = pt.retry_count + 1;
let error_message = payment_attempt
.error
.as_ref()
.map(|details| details.message.clone());
let error_code = payment_attempt
.error
.as_ref()
.map(|details| details.code.clone());
let connector_name = payment_attempt
.connector
.clone()
.ok_or(errors::RecoveryError::ValueNotFound)
.attach_printable("unable to derive payment connector from payment attempt")?;
let gsm_record = helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|gsm_record| gsm_record.error_category)
.map(|gsm_error_category| {
gsm_error_category == common_enums::ErrorCategory::HardDecline
})
.unwrap_or(false);
let schedule_time = revenue_recovery_payment_data
.get_schedule_time_based_on_retry_type(
state,
merchant_id,
next_retry_count,
payment_attempt,
payment_intent,
is_hard_decline,
)
.await;
match schedule_time {
Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)),
None => Ok(Self::TerminalFailure(payment_attempt.clone())),
}
}
}
/// Reopen calculate workflow when payment fails
pub async fn reopen_calculate_workflow_on_payment_failure(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_intent: &PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<()> {
let db = &*state.store;
let id = payment_intent.id.clone();
let task = revenue_recovery_core::CALCULATE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
payment_attempt_id: latest_attempt_id.clone(),
..old_tracking_data
};
let tracking_data = serde_json::to_value(new_tracking_data)
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to serialize the tracking data for process tracker")?;
// Construct the process tracker ID for CALCULATE_WORKFLOW
let process_tracker_id = format!("{}_{}_{}", runner, task, id.get_string_repr());
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"Attempting to reopen CALCULATE_WORKFLOW on payment failure"
);
// Find the existing CALCULATE_WORKFLOW process tracker
let calculate_process = db
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to find CALCULATE_WORKFLOW process tracker")?;
match calculate_process {
Some(process) => {
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
current_status = %process.business_status,
current_retry_count = process.retry_count,
"Found existing CALCULATE_WORKFLOW, updating status and retry count"
);
// Update the process tracker to reopen the calculate workflow
// 1. Change status from "finish" to "pending"
// 2. Increase retry count by 1
// 3. Set business status to QUEUED
// 4. Schedule for immediate execution
let new_retry_count = process.retry_count + 1;
let new_schedule_time = common_utils::date_time::now()
+ time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.reopen_workflow_buffer_time_in_seconds,
);
let pt_update = storage::ProcessTrackerUpdate::Update {
name: Some(task.to_string()),
retry_count: Some(new_retry_count),
schedule_time: Some(new_schedule_time),
tracking_data: Some(tracking_data),
business_status: Some(String::from(business_status::PENDING)),
status: Some(common_enums::ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
db.update_process(process.clone(), pt_update)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update CALCULATE_WORKFLOW process tracker")?;
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
new_retry_count = new_retry_count,
new_schedule_time = %new_schedule_time,
"Successfully reopened CALCULATE_WORKFLOW with increased retry count"
);
}
None => {
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"CALCULATE_WORKFLOW process tracker not found, creating new entry"
);
let task = "CALCULATE_WORKFLOW";
let db = &*state.store;
// Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id}
let process_tracker_id = format!("{runner}_{task}_{}", id.get_string_repr());
// Set scheduled time to current time + buffer time set in configuration
let schedule_time = common_utils::date_time::now()
+ time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.reopen_workflow_buffer_time_in_seconds,
);
let new_retry_count = process.retry_count + 1;
// Check if a process tracker entry already exists for this payment intent
let existing_entry = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable(
"Failed to check for existing calculate workflow process tracker entry",
)?;
// No entry exists - create a new one
router_env::logger::info!(
"No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry... ",
id.get_string_repr()
);
let tag = ["PCR"];
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_entry = storage::ProcessTrackerNew::new(
&process_tracker_id,
task,
runner,
tag,
process.tracking_data.clone(),
Some(new_retry_count),
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to construct calculate workflow process tracker entry")?;
// Insert into process tracker with status New
db.as_scheduler()
.insert_process(process_tracker_entry)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable(
"Failed to enter calculate workflow process_tracker_entry in DB",
)?;
router_env::logger::info!(
"Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}",
id.get_string_repr()
);
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"Successfully created new CALCULATE_WORKFLOW entry using perform_calculate_workflow"
);
}
}
Ok(())
}
// TODO: Move these to impl based functions
async fn record_back_to_billing_connector(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
billing_mca: &merchant_connector_account::MerchantConnectorAccount,
) -> RecoveryResult<()> {
logger::info!("Entering record_back_to_billing_connector");
let connector_name = billing_mca.connector_name.to_string();
let connector_data = api_types::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api_types::GetToken::Connector,
Some(billing_mca.get_id()),
)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("invalid connector name received in billing merchant connector account")?;
let connector_integration: services::BoxedRevenueRecoveryRecordBackInterface<
router_flow_types::InvoiceRecordBack,
revenue_recovery_request::InvoiceRecordBackRequest,
revenue_recovery_response::InvoiceRecordBackResponse,
> = connector_data.connector.get_connector_integration();
let router_data = construct_invoice_record_back_router_data(
state,
billing_mca,
payment_attempt,
payment_intent,
)?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed while handling response of record back to billing connector")?;
match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
router_env::logger::error!(?error);
Err(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed while recording back to billing connector")
}
}?;
Ok(())
}
pub fn construct_invoice_record_back_router_data(
state: &SessionState,
billing_mca: &merchant_connector_account::MerchantConnectorAccount,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> RecoveryResult<hyperswitch_domain_models::types::InvoiceRecordBackRouterData> {
logger::info!("Entering construct_invoice_record_back_router_data");
let auth_type: types::ConnectorAuthType =
helpers::MerchantConnectorAccountType::DbVal(Box::new(billing_mca.clone()))
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)?;
let merchant_reference_id = payment_intent
.merchant_reference_id
.clone()
.ok_or(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable(
"Merchant reference id not found while recording back to billing connector",
)?;
let connector_name = billing_mca.get_connector_name_as_string();
let connector = common_enums::connector_enums::Connector::from_str(connector_name.as_str())
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Cannot find connector from the connector_name")?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector,
)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable(format!(
"cannot find connector params for this connector {connector} in this flow",
))?;
let router_data = router_data_v2::RouterDataV2 {
flow: PhantomData::<router_flow_types::InvoiceRecordBack>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::InvoiceRecordBackData {
connector_meta_data: None,
},
connector_auth_type: auth_type,
request: revenue_recovery_request::InvoiceRecordBackRequest {
merchant_reference_id,
amount: payment_attempt.get_total_amount(),
currency: payment_intent.amount_details.currency,
payment_method_type: Some(payment_attempt.payment_method_subtype),
attempt_status: payment_attempt.status,
connector_transaction_id: payment_attempt
.connector_payment_id
.as_ref()
.map(|id| common_utils::types::ConnectorTransactionId::TxnId(id.clone())),
connector_params,
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data = flow_common_types::InvoiceRecordBackData::to_old_router_data(router_data)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Cannot construct record back router data")?;
Ok(old_router_data)
}
pub fn get_payment_processor_token_id_from_payment_attempt(
payment_attempt: &PaymentAttempt,
) -> Option<String> {
let used_token = payment_attempt
.connector_token_details
.as_ref()
.and_then(|t| t.connector_mandate_id.clone());
logger::info!("Used token in the payment attempt : {:?}", used_token);
used_token
}
pub struct RevenueRecoveryOutgoingWebhook;
impl RevenueRecoveryOutgoingWebhook {
#[allow(clippy::too_many_arguments)]
pub async fn send_outgoing_webhook_based_on_revenue_recovery_status(
state: &SessionState,
event_class: common_enums::EventClass,
event_status: common_enums::EventType,
payment_intent: &PaymentIntent,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_attempt_id: String,
payments_response: ApplicationResponse<api_models::payments::PaymentsResponse>,
) -> RecoveryResult<()> {
match payments_response {
ApplicationResponse::JsonWithHeaders((response, _headers)) => {
let outgoing_webhook_content =
api_models::webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(
response,
));
create_event_and_trigger_outgoing_webhook(
state.clone(),
profile.clone(),
merchant_context.get_merchant_key_store(),
event_status,
event_class,
payment_attempt_id,
enums::EventObjectType::PaymentDetails,
outgoing_webhook_content,
payment_intent.created_at,
)
.await
.change_context(errors::RecoveryError::InvalidTask)
.attach_printable("Failed to send out going webhook")?;
Ok(())
}
_other_variant => {
// Handle other successful response types if needed
logger::warn!("Unexpected application response variant for outgoing webhook");
Err(errors::RecoveryError::RevenueRecoveryOutgoingWebhookFailed.into())
}
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/revenue_recovery/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_5543985855221212387 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/errors/customers_error_response.rs
// Contains: 0 structs, 1 enums
use http::StatusCode;
#[derive(Debug, thiserror::Error)]
pub enum CustomersErrorResponse {
#[error("Customer has already been redacted")]
CustomerRedacted,
#[error("Something went wrong")]
InternalServerError,
#[error("Invalid request data: {message}")]
InvalidRequestData { message: String },
#[error("Customer has already been redacted")]
MandateActive,
#[error("Customer does not exist in our records")]
CustomerNotFound,
#[error("Customer with the given customer id already exists")]
CustomerAlreadyExists,
}
impl actix_web::ResponseError for CustomersErrorResponse {
fn status_code(&self) -> StatusCode {
common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
self,
)
.status_code()
}
fn error_response(&self) -> actix_web::HttpResponse {
common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
self,
)
.error_response()
}
}
// should be removed hola bola
| {
"crate": "router",
"file": "crates/router/src/core/errors/customers_error_response.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_6496136927316273885 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/errors/user.rs
// Contains: 0 structs, 1 enums
use common_utils::errors::CustomResult;
use crate::services::ApplicationResponse;
pub type UserResult<T> = CustomResult<T, UserErrors>;
pub type UserResponse<T> = CustomResult<ApplicationResponse<T>, UserErrors>;
pub mod sample_data;
#[derive(Debug, thiserror::Error)]
pub enum UserErrors {
#[error("User InternalServerError")]
InternalServerError,
#[error("InvalidCredentials")]
InvalidCredentials,
#[error("UserNotFound")]
UserNotFound,
#[error("UserExists")]
UserExists,
#[error("LinkInvalid")]
LinkInvalid,
#[error("UnverifiedUser")]
UnverifiedUser,
#[error("InvalidOldPassword")]
InvalidOldPassword,
#[error("EmailParsingError")]
EmailParsingError,
#[error("NameParsingError")]
NameParsingError,
#[error("PasswordParsingError")]
PasswordParsingError,
#[error("UserAlreadyVerified")]
UserAlreadyVerified,
#[error("CompanyNameParsingError")]
CompanyNameParsingError,
#[error("MerchantAccountCreationError: {0}")]
MerchantAccountCreationError(String),
#[error("InvalidEmailError")]
InvalidEmailError,
#[error("DuplicateOrganizationId")]
DuplicateOrganizationId,
#[error("MerchantIdNotFound")]
MerchantIdNotFound,
#[error("MetadataAlreadySet")]
MetadataAlreadySet,
#[error("InvalidRoleId")]
InvalidRoleId,
#[error("InvalidRoleOperation")]
InvalidRoleOperation,
#[error("IpAddressParsingFailed")]
IpAddressParsingFailed,
#[error("InvalidMetadataRequest")]
InvalidMetadataRequest,
#[error("MerchantIdParsingError")]
MerchantIdParsingError,
#[error("ChangePasswordError")]
ChangePasswordError,
#[error("InvalidDeleteOperation")]
InvalidDeleteOperation,
#[error("MaxInvitationsError")]
MaxInvitationsError,
#[error("RoleNotFound")]
RoleNotFound,
#[error("InvalidRoleOperationWithMessage")]
InvalidRoleOperationWithMessage(String),
#[error("RoleNameParsingError")]
RoleNameParsingError,
#[error("RoleNameAlreadyExists")]
RoleNameAlreadyExists,
#[error("TotpNotSetup")]
TotpNotSetup,
#[error("InvalidTotp")]
InvalidTotp,
#[error("TotpRequired")]
TotpRequired,
#[error("InvalidRecoveryCode")]
InvalidRecoveryCode,
#[error("TwoFactorAuthRequired")]
TwoFactorAuthRequired,
#[error("TwoFactorAuthNotSetup")]
TwoFactorAuthNotSetup,
#[error("TOTP secret not found")]
TotpSecretNotFound,
#[error("User auth method already exists")]
UserAuthMethodAlreadyExists,
#[error("Invalid user auth method operation")]
InvalidUserAuthMethodOperation,
#[error("Auth config parsing error")]
AuthConfigParsingError,
#[error("Invalid SSO request")]
SSOFailed,
#[error("profile_id missing in JWT")]
JwtProfileIdMissing,
#[error("Maximum attempts reached for TOTP")]
MaxTotpAttemptsReached,
#[error("Maximum attempts reached for Recovery Code")]
MaxRecoveryCodeAttemptsReached,
#[error("Forbidden tenant id")]
ForbiddenTenantId,
#[error("Error Uploading file to Theme Storage")]
ErrorUploadingFile,
#[error("Error Retrieving file from Theme Storage")]
ErrorRetrievingFile,
#[error("Theme not found")]
ThemeNotFound,
#[error("Theme with lineage already exists")]
ThemeAlreadyExists,
#[error("Invalid field: {0} in lineage")]
InvalidThemeLineage(String),
#[error("Missing required field: email_config")]
MissingEmailConfig,
#[error("Invalid Auth Method Operation: {0}")]
InvalidAuthMethodOperationWithMessage(String),
#[error("Invalid Clone Connector Operation: {0}")]
InvalidCloneConnectorOperation(String),
#[error("Error cloning connector: {0}")]
ErrorCloningConnector(String),
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
let sub_code = "UR";
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
}
Self::InvalidCredentials => {
AER::Unauthorized(ApiError::new(sub_code, 1, self.get_error_message(), None))
}
Self::UserNotFound => {
AER::Unauthorized(ApiError::new(sub_code, 2, self.get_error_message(), None))
}
Self::UserExists => {
AER::BadRequest(ApiError::new(sub_code, 3, self.get_error_message(), None))
}
Self::LinkInvalid => {
AER::Unauthorized(ApiError::new(sub_code, 4, self.get_error_message(), None))
}
Self::UnverifiedUser => {
AER::Unauthorized(ApiError::new(sub_code, 5, self.get_error_message(), None))
}
Self::InvalidOldPassword => {
AER::BadRequest(ApiError::new(sub_code, 6, self.get_error_message(), None))
}
Self::EmailParsingError => {
AER::BadRequest(ApiError::new(sub_code, 7, self.get_error_message(), None))
}
Self::NameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 8, self.get_error_message(), None))
}
Self::PasswordParsingError => {
AER::BadRequest(ApiError::new(sub_code, 9, self.get_error_message(), None))
}
Self::UserAlreadyVerified => {
AER::Unauthorized(ApiError::new(sub_code, 11, self.get_error_message(), None))
}
Self::CompanyNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None))
}
Self::MerchantAccountCreationError(_) => AER::InternalServerError(ApiError::new(
sub_code,
15,
self.get_error_message(),
None,
)),
Self::InvalidEmailError => {
AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None))
}
Self::MerchantIdNotFound => {
AER::BadRequest(ApiError::new(sub_code, 18, self.get_error_message(), None))
}
Self::MetadataAlreadySet => {
AER::BadRequest(ApiError::new(sub_code, 19, self.get_error_message(), None))
}
Self::DuplicateOrganizationId => AER::InternalServerError(ApiError::new(
sub_code,
21,
self.get_error_message(),
None,
)),
Self::InvalidRoleId => {
AER::BadRequest(ApiError::new(sub_code, 22, self.get_error_message(), None))
}
Self::InvalidRoleOperation => {
AER::BadRequest(ApiError::new(sub_code, 23, self.get_error_message(), None))
}
Self::IpAddressParsingFailed => AER::InternalServerError(ApiError::new(
sub_code,
24,
self.get_error_message(),
None,
)),
Self::InvalidMetadataRequest => {
AER::BadRequest(ApiError::new(sub_code, 26, self.get_error_message(), None))
}
Self::MerchantIdParsingError => {
AER::BadRequest(ApiError::new(sub_code, 28, self.get_error_message(), None))
}
Self::ChangePasswordError => {
AER::BadRequest(ApiError::new(sub_code, 29, self.get_error_message(), None))
}
Self::InvalidDeleteOperation => {
AER::BadRequest(ApiError::new(sub_code, 30, self.get_error_message(), None))
}
Self::MaxInvitationsError => {
AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None))
}
Self::RoleNotFound => {
AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None))
}
Self::InvalidRoleOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None))
}
Self::RoleNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 34, self.get_error_message(), None))
}
Self::RoleNameAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None))
}
Self::TotpNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 36, self.get_error_message(), None))
}
Self::InvalidTotp => {
AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None))
}
Self::TotpRequired => {
AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None))
}
Self::InvalidRecoveryCode => {
AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None))
}
Self::TwoFactorAuthRequired => {
AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None))
}
Self::TwoFactorAuthNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None))
}
Self::TotpSecretNotFound => {
AER::BadRequest(ApiError::new(sub_code, 42, self.get_error_message(), None))
}
Self::UserAuthMethodAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 43, self.get_error_message(), None))
}
Self::InvalidUserAuthMethodOperation => {
AER::BadRequest(ApiError::new(sub_code, 44, self.get_error_message(), None))
}
Self::AuthConfigParsingError => {
AER::BadRequest(ApiError::new(sub_code, 45, self.get_error_message(), None))
}
Self::SSOFailed => {
AER::BadRequest(ApiError::new(sub_code, 46, self.get_error_message(), None))
}
Self::JwtProfileIdMissing => {
AER::Unauthorized(ApiError::new(sub_code, 47, self.get_error_message(), None))
}
Self::MaxTotpAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 48, self.get_error_message(), None))
}
Self::MaxRecoveryCodeAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 49, self.get_error_message(), None))
}
Self::ForbiddenTenantId => {
AER::BadRequest(ApiError::new(sub_code, 50, self.get_error_message(), None))
}
Self::ErrorUploadingFile => AER::InternalServerError(ApiError::new(
sub_code,
51,
self.get_error_message(),
None,
)),
Self::ErrorRetrievingFile => AER::InternalServerError(ApiError::new(
sub_code,
52,
self.get_error_message(),
None,
)),
Self::ThemeNotFound => {
AER::NotFound(ApiError::new(sub_code, 53, self.get_error_message(), None))
}
Self::ThemeAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 54, self.get_error_message(), None))
}
Self::InvalidThemeLineage(_) => {
AER::BadRequest(ApiError::new(sub_code, 55, self.get_error_message(), None))
}
Self::MissingEmailConfig => {
AER::BadRequest(ApiError::new(sub_code, 56, self.get_error_message(), None))
}
Self::InvalidAuthMethodOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 57, self.get_error_message(), None))
}
Self::InvalidCloneConnectorOperation(_) => {
AER::BadRequest(ApiError::new(sub_code, 58, self.get_error_message(), None))
}
Self::ErrorCloningConnector(_) => AER::InternalServerError(ApiError::new(
sub_code,
59,
self.get_error_message(),
None,
)),
}
}
}
impl UserErrors {
pub fn get_error_message(&self) -> String {
match self {
Self::InternalServerError => "Something went wrong".to_string(),
Self::InvalidCredentials => "Incorrect email or password".to_string(),
Self::UserNotFound => "Email doesn’t exist. Register".to_string(),
Self::UserExists => "An account already exists with this email".to_string(),
Self::LinkInvalid => "Invalid or expired link".to_string(),
Self::UnverifiedUser => "Kindly verify your account".to_string(),
Self::InvalidOldPassword => {
"Old password incorrect. Please enter the correct password".to_string()
}
Self::EmailParsingError => "Invalid Email".to_string(),
Self::NameParsingError => "Invalid Name".to_string(),
Self::PasswordParsingError => "Invalid Password".to_string(),
Self::UserAlreadyVerified => "User already verified".to_string(),
Self::CompanyNameParsingError => "Invalid Company Name".to_string(),
Self::MerchantAccountCreationError(error_message) => error_message.to_string(),
Self::InvalidEmailError => "Invalid Email".to_string(),
Self::MerchantIdNotFound => "Invalid Merchant ID".to_string(),
Self::MetadataAlreadySet => "Metadata already set".to_string(),
Self::DuplicateOrganizationId => {
"An Organization with the id already exists".to_string()
}
Self::InvalidRoleId => "Invalid Role ID".to_string(),
Self::InvalidRoleOperation => "User Role Operation Not Supported".to_string(),
Self::IpAddressParsingFailed => "Something went wrong".to_string(),
Self::InvalidMetadataRequest => "Invalid Metadata Request".to_string(),
Self::MerchantIdParsingError => "Invalid Merchant Id".to_string(),
Self::ChangePasswordError => "Old and new password cannot be same".to_string(),
Self::InvalidDeleteOperation => "Delete Operation Not Supported".to_string(),
Self::MaxInvitationsError => "Maximum invite count per request exceeded".to_string(),
Self::RoleNotFound => "Role Not Found".to_string(),
Self::InvalidRoleOperationWithMessage(error_message) => error_message.to_string(),
Self::RoleNameParsingError => "Invalid Role Name".to_string(),
Self::RoleNameAlreadyExists => "Role name already exists".to_string(),
Self::TotpNotSetup => "TOTP not setup".to_string(),
Self::InvalidTotp => "Invalid TOTP".to_string(),
Self::TotpRequired => "TOTP required".to_string(),
Self::InvalidRecoveryCode => "Invalid Recovery Code".to_string(),
Self::MaxTotpAttemptsReached => "Maximum attempts reached for TOTP".to_string(),
Self::MaxRecoveryCodeAttemptsReached => {
"Maximum attempts reached for Recovery Code".to_string()
}
Self::TwoFactorAuthRequired => "Two factor auth required".to_string(),
Self::TwoFactorAuthNotSetup => "Two factor auth not setup".to_string(),
Self::TotpSecretNotFound => "TOTP secret not found".to_string(),
Self::UserAuthMethodAlreadyExists => "User auth method already exists".to_string(),
Self::InvalidUserAuthMethodOperation => {
"Invalid user auth method operation".to_string()
}
Self::AuthConfigParsingError => "Auth config parsing error".to_string(),
Self::SSOFailed => "Invalid SSO request".to_string(),
Self::JwtProfileIdMissing => "profile_id missing in JWT".to_string(),
Self::ForbiddenTenantId => "Forbidden tenant id".to_string(),
Self::ErrorUploadingFile => "Error Uploading file to Theme Storage".to_string(),
Self::ErrorRetrievingFile => "Error Retrieving file from Theme Storage".to_string(),
Self::ThemeNotFound => "Theme not found".to_string(),
Self::ThemeAlreadyExists => "Theme with lineage already exists".to_string(),
Self::InvalidThemeLineage(field_name) => {
format!("Invalid field: {field_name} in lineage")
}
Self::MissingEmailConfig => "Missing required field: email_config".to_string(),
Self::InvalidAuthMethodOperationWithMessage(operation) => {
format!("Invalid Auth Method Operation: {operation}")
}
Self::InvalidCloneConnectorOperation(operation) => {
format!("Invalid Clone Connector Operation: {operation}")
}
Self::ErrorCloningConnector(error_message) => {
format!("Error cloning connector: {error_message}")
}
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/errors/user.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-1768214410158752403 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/errors/chat.rs
// Contains: 0 structs, 1 enums
#[derive(Debug, thiserror::Error)]
pub enum ChatErrors {
#[error("User InternalServerError")]
InternalServerError,
#[error("Missing Config error")]
MissingConfigError,
#[error("Chat response deserialization failed")]
ChatResponseDeserializationFailed,
#[error("Unauthorized access")]
UnauthorizedAccess,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ChatErrors {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
let sub_code = "AI";
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
}
Self::MissingConfigError => {
AER::InternalServerError(ApiError::new(sub_code, 1, self.get_error_message(), None))
}
Self::ChatResponseDeserializationFailed => {
AER::BadRequest(ApiError::new(sub_code, 2, self.get_error_message(), None))
}
Self::UnauthorizedAccess => {
AER::Unauthorized(ApiError::new(sub_code, 3, self.get_error_message(), None))
}
}
}
}
impl ChatErrors {
pub fn get_error_message(&self) -> String {
match self {
Self::InternalServerError => "Something went wrong".to_string(),
Self::MissingConfigError => "Missing webhook url".to_string(),
Self::ChatResponseDeserializationFailed => "Failed to parse chat response".to_string(),
Self::UnauthorizedAccess => "Not authorized to access the resource".to_string(),
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/errors/chat.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_8460326169540230515 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/errors/user/sample_data.rs
// Contains: 0 structs, 1 enums
use api_models::errors::types::{ApiError, ApiErrorResponse};
use common_utils::errors::{CustomResult, ErrorSwitch, ErrorSwitchFrom};
use storage_impl::errors::StorageError;
pub type SampleDataResult<T> = CustomResult<T, SampleDataError>;
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
pub enum SampleDataError {
#[error["Internal Server Error"]]
InternalServerError,
#[error("Data Does Not Exist")]
DataDoesNotExist,
#[error("Invalid Parameters")]
InvalidParameters,
#[error["Invalid Records"]]
InvalidRange,
}
impl ErrorSwitch<ApiErrorResponse> for SampleDataError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::InternalServerError => ApiErrorResponse::InternalServerError(ApiError::new(
"SD",
0,
"Something went wrong",
None,
)),
Self::DataDoesNotExist => ApiErrorResponse::NotFound(ApiError::new(
"SD",
1,
"Sample Data not present for given request",
None,
)),
Self::InvalidParameters => ApiErrorResponse::BadRequest(ApiError::new(
"SD",
2,
"Invalid parameters to generate Sample Data",
None,
)),
Self::InvalidRange => ApiErrorResponse::BadRequest(ApiError::new(
"SD",
3,
"Records to be generated should be between range 10 and 100",
None,
)),
}
}
}
impl ErrorSwitchFrom<StorageError> for SampleDataError {
fn switch_from(error: &StorageError) -> Self {
match matches!(error, StorageError::ValueNotFound(_)) {
true => Self::DataDoesNotExist,
false => Self::InternalServerError,
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/errors/user/sample_data.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4365295691809446099 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/webhooks/network_tokenization_incoming.rs
// Contains: 0 structs, 1 enums
use std::str::FromStr;
use ::payment_methods::controller::PaymentMethodsController;
use api_models::webhooks::WebhookResponseTracker;
use async_trait::async_trait;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, ValueExt},
id_type,
};
use error_stack::{report, ResultExt};
use http::HeaderValue;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
configs::settings,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payment_methods::cards,
},
logger,
routes::{app::SessionStateInfo, SessionState},
types::{
api, domain, payment_methods as pm_types,
storage::{self, enums},
},
utils::{self as helper_utils, ext_traits::OptionExt},
};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum NetworkTokenWebhookResponse {
PanMetadataUpdate(pm_types::PanMetadataUpdateBody),
NetworkTokenMetadataUpdate(pm_types::NetworkTokenMetaDataUpdateBody),
}
impl NetworkTokenWebhookResponse {
fn get_network_token_requestor_ref_id(&self) -> String {
match self {
Self::PanMetadataUpdate(data) => data.card.card_reference.clone(),
Self::NetworkTokenMetadataUpdate(data) => data.token.card_reference.clone(),
}
}
pub fn get_response_data(self) -> Box<dyn NetworkTokenWebhookResponseExt> {
match self {
Self::PanMetadataUpdate(data) => Box::new(data),
Self::NetworkTokenMetadataUpdate(data) => Box::new(data),
}
}
pub async fn fetch_merchant_id_payment_method_id_customer_id_from_callback_mapper(
&self,
state: &SessionState,
) -> RouterResult<(id_type::MerchantId, String, id_type::CustomerId)> {
let network_token_requestor_ref_id = &self.get_network_token_requestor_ref_id();
let db = &*state.store;
let callback_mapper_data = db
.find_call_back_mapper_by_id(network_token_requestor_ref_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch callback mapper data")?;
Ok(callback_mapper_data
.data
.get_network_token_webhook_details())
}
}
pub fn get_network_token_resource_object(
request_details: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::NetworkTokenizationError> {
let response: NetworkTokenWebhookResponse = request_details
.body
.parse_struct("NetworkTokenWebhookResponse")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
Ok(Box::new(response))
}
#[async_trait]
pub trait NetworkTokenWebhookResponseExt {
fn decrypt_payment_method_data(
&self,
payment_method: &domain::PaymentMethod,
) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse>;
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse>;
}
#[async_trait]
impl NetworkTokenWebhookResponseExt for pm_types::PanMetadataUpdateBody {
fn decrypt_payment_method_data(
&self,
payment_method: &domain::PaymentMethod,
) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse> {
let decrypted_data = payment_method
.payment_method_data
.clone()
.map(|payment_method_data| payment_method_data.into_inner().expose())
.and_then(|val| {
val.parse_value::<api::payment_methods::PaymentMethodsData>("PaymentMethodsData")
.map_err(|err| logger::error!(?err, "Failed to parse PaymentMethodsData"))
.ok()
})
.and_then(|pmd| match pmd {
api::payment_methods::PaymentMethodsData::Card(token) => {
Some(api::payment_methods::CardDetailFromLocker::from(token))
}
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted token object from db")?;
Ok(decrypted_data)
}
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let decrypted_data = self.decrypt_payment_method_data(payment_method)?;
handle_metadata_update(
state,
&self.card,
payment_method
.locker_id
.clone()
.get_required_value("locker_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id is not found for the payment method")?,
payment_method,
merchant_context,
decrypted_data,
true,
)
.await
}
}
#[async_trait]
impl NetworkTokenWebhookResponseExt for pm_types::NetworkTokenMetaDataUpdateBody {
fn decrypt_payment_method_data(
&self,
payment_method: &domain::PaymentMethod,
) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse> {
let decrypted_data = payment_method
.network_token_payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|val| {
val.parse_value::<api::payment_methods::PaymentMethodsData>("PaymentMethodsData")
.map_err(|err| logger::error!(?err, "Failed to parse PaymentMethodsData"))
.ok()
})
.and_then(|pmd| match pmd {
api::payment_methods::PaymentMethodsData::Card(token) => {
Some(api::payment_methods::CardDetailFromLocker::from(token))
}
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted token object from db")?;
Ok(decrypted_data)
}
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let decrypted_data = self.decrypt_payment_method_data(payment_method)?;
handle_metadata_update(
state,
&self.token,
payment_method
.network_token_locker_id
.clone()
.get_required_value("locker_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id is not found for the payment method")?,
payment_method,
merchant_context,
decrypted_data,
true,
)
.await
}
}
pub struct Authorization {
header: Option<HeaderValue>,
}
impl Authorization {
pub fn new(header: Option<&HeaderValue>) -> Self {
Self {
header: header.cloned(),
}
}
pub async fn verify_webhook_source(
self,
nt_service: &settings::NetworkTokenizationService,
) -> CustomResult<(), errors::ApiErrorResponse> {
let secret = nt_service.webhook_source_verification_key.clone();
let source_verified = match self.header {
Some(authorization_header) => match authorization_header.to_str() {
Ok(header_value) => Ok(header_value == secret.expose()),
Err(err) => {
logger::error!(?err, "Failed to parse authorization header");
Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)
}
},
None => Ok(false),
}?;
logger::info!(source_verified=?source_verified);
helper_utils::when(!source_verified, || {
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
})?;
Ok(())
}
}
#[allow(clippy::too_many_arguments)]
pub async fn handle_metadata_update(
state: &SessionState,
metadata: &pm_types::NetworkTokenRequestorData,
locker_id: String,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
decrypted_data: api::payment_methods::CardDetailFromLocker,
is_pan_update: bool,
) -> RouterResult<WebhookResponseTracker> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = &payment_method.customer_id;
let payment_method_id = payment_method.get_id().clone();
let status = payment_method.status;
match metadata.is_update_required(decrypted_data) {
false => {
logger::info!(
"No update required for payment method {} for locker_id {}",
payment_method.get_id(),
locker_id
);
Ok(WebhookResponseTracker::PaymentMethod {
payment_method_id,
status,
})
}
true => {
let mut card = cards::get_card_from_locker(state, customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch token information from the locker")?;
card.card_exp_year = metadata.expiry_year.clone();
card.card_exp_month = metadata.expiry_month.clone();
let card_network = card
.card_brand
.clone()
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card network",
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Card Network stored in vault")?;
let card_data = api::payment_methods::CardDetail::from((card, card_network));
let payment_method_request: api::payment_methods::PaymentMethodCreate =
PaymentMethodCreateWrapper::from((&card_data, payment_method)).get_inner();
let pm_cards = cards::PmCards {
state,
merchant_context,
};
pm_cards
.delete_card_from_locker(customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete network token")?;
let (res, _) = pm_cards
.add_card_to_locker(payment_method_request, &card_data, customer_id, None)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add network token")?;
let pm_details = res.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod::from((card.clone(), None)),
)
});
let key_manager_state = state.into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_details
.async_map(|pm_card| {
cards::create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_card,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = if is_pan_update {
storage::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: Some(res.payment_method_id),
payment_method_data: pm_data_encrypted.map(Into::into),
status: None,
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
}
} else {
storage::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: None,
payment_method_data: None,
status: None,
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
network_token_requestor_reference_id: None,
network_token_locker_id: Some(res.payment_method_id),
network_token_payment_method_data: pm_data_encrypted.map(Into::into),
}
};
let db = &*state.store;
db.update_payment_method(
&key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method.clone(),
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the payment method")?;
Ok(WebhookResponseTracker::PaymentMethod {
payment_method_id,
status,
})
}
}
}
pub struct PaymentMethodCreateWrapper(pub api::payment_methods::PaymentMethodCreate);
impl From<(&api::payment_methods::CardDetail, &domain::PaymentMethod)>
for PaymentMethodCreateWrapper
{
fn from(
(data, payment_method): (&api::payment_methods::CardDetail, &domain::PaymentMethod),
) -> Self {
Self(api::payment_methods::PaymentMethodCreate {
customer_id: Some(payment_method.customer_id.clone()),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
payment_method_issuer: payment_method.payment_method_issuer.clone(),
payment_method_issuer_code: payment_method.payment_method_issuer_code,
metadata: payment_method.metadata.clone(),
payment_method_data: None,
connector_mandate_details: None,
client_secret: None,
billing: None,
card: Some(data.clone()),
card_network: data
.card_network
.clone()
.map(|card_network| card_network.to_string()),
bank_transfer: None,
wallet: None,
network_transaction_id: payment_method.network_transaction_id.clone(),
})
}
}
impl PaymentMethodCreateWrapper {
fn get_inner(self) -> api::payment_methods::PaymentMethodCreate {
self.0
}
}
pub async fn fetch_merchant_account_for_network_token_webhooks(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> RouterResult<domain::MerchantContext> {
let db = &*state.store;
let key_manager_state = &(state).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store,
)));
Ok(merchant_context)
}
pub async fn fetch_payment_method_for_network_token_webhooks(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
) -> RouterResult<domain::PaymentMethod> {
let db = &*state.store;
let key_manager_state = &(state).into();
let payment_method = db
.find_payment_method(
key_manager_state,
key_store,
payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the payment method")?;
Ok(payment_method)
}
| {
"crate": "router",
"file": "crates/router/src/core/webhooks/network_tokenization_incoming.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-6451571917243214356 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/webhooks/outgoing.rs
// Contains: 0 structs, 1 enums
use std::collections::HashMap;
use api_models::{
webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent},
webhooks,
};
use common_utils::{
ext_traits::{Encode, StringExt},
request::RequestContent,
type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use hyperswitch_interfaces::consts;
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use super::{types, utils, MERCHANT_ID};
#[cfg(feature = "stripe")]
use crate::compatibility::stripe::webhooks as stripe_webhooks;
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
db::StorageInterface,
events::outgoing_webhook_logs::{
OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric,
},
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api,
domain::{self},
storage::{self, enums},
transformers::ForeignFrom,
},
utils::{OptionExt, ValueExt},
workflows::outgoing_webhook_retry,
};
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let webhook_url_result = get_webhook_url_from_business_profile(&business_profile);
if !state.conf.webhooks.outgoing_enabled
|| webhook_url_result.is_err()
|| webhook_url_result.as_ref().is_ok_and(String::is_empty)
{
logger::debug!(
business_profile_id=?business_profile.get_id(),
%idempotent_event_id,
"Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
could not be obtained; skipping outgoing webhooks for event"
);
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content =
get_outgoing_webhook_request(&merchant_context, outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
request_content
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(Secret::new)?,
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let lock_value = utils::perform_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
if lock_value.is_none() {
return Ok(());
}
if (state
.store
.find_event_by_merchant_id_idempotent_event_id(
key_manager_state,
&merchant_id,
&idempotent_event_id,
merchant_context.get_merchant_key_store(),
)
.await)
.is_ok()
{
logger::debug!(
"Event with idempotent ID `{idempotent_event_id}` already exists in the database"
);
utils::free_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
lock_value,
)
.await?;
return Ok(());
}
let event_insert_result = state
.store
.insert_event(
key_manager_state,
new_event,
merchant_context.get_merchant_key_store(),
)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}?;
utils::free_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
lock_value,
)
.await?;
let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
&*state.store,
&business_profile,
&event,
)
.await
.inspect_err(|error| {
logger::error!(
?error,
"Failed to add outgoing webhook retry task to process tracker"
);
})
.ok();
let cloned_key_store = merchant_context.get_merchant_key_store().clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
process_tracker,
))
.await;
}
.in_current_span(),
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn trigger_webhook_and_raise_event(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
content: Option<api::OutgoingWebhookContent>,
process_tracker: Option<storage::ProcessTracker>,
) {
logger::debug!(
event_id=%event.event_id,
idempotent_event_id=?event.idempotent_event_id,
initial_attempt_id=?event.initial_attempt_id,
"Attempting to send webhook"
);
let merchant_id = business_profile.merchant_id.clone();
let trigger_webhook_result = trigger_webhook_to_merchant(
state.clone(),
business_profile,
merchant_key_store,
event.clone(),
request_content,
delivery_attempt,
process_tracker,
)
.await;
let _ = raise_webhooks_analytics_event(
state,
trigger_webhook_result,
content,
merchant_id,
event,
merchant_key_store,
)
.await;
}
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_url = match (
get_webhook_url_from_business_profile(&business_profile),
process_tracker.clone(),
) {
(Ok(webhook_url), _) => Ok(webhook_url),
(Err(error), Some(process_tracker)) => {
if !error
.current_context()
.is_webhook_delivery_retryable_error()
{
logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
)?;
}
Err(error)
}
(Err(error), None) => Err(error),
}?;
let event_id = event.event_id;
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, value.into_masked()))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(RequestContent::RawBytes(
request_content.body.expose().into_bytes(),
))
.build();
let response = state
.api_client
.send_request(&state, request, None, false)
.await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
enums::WebhookDeliveryAttempt::AutomaticRetry => {
let process_tracker = process_tracker
.get_required_value("process_tracker")
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)
.attach_printable("`process_tracker` is unavailable in automatic retry flow")?;
match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
}
}
}
enums::WebhookDeliveryAttempt::ManualRetry => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
increment_webhook_outgoing_received_count(&business_profile.merchant_id);
} else {
error_response_handler(
state,
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
}
Ok(())
}
async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>,
content: Option<api::OutgoingWebhookContent>,
merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) {
let key_manager_state: &KeyManagerState = &(&state).into();
let event_id = event.event_id;
let error = if let Err(error) = trigger_webhook_result {
logger::error!(?error, "Failed to send webhook to merchant");
serde_json::to_value(error.current_context())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.inspect_err(|error| {
logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");
})
.ok()
} else {
None
};
let outgoing_webhook_event_content = content
.as_ref()
.and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content)
.or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata));
// Fetch updated_event from db
let updated_event = state
.store
.find_event_by_merchant_id_event_id(
key_manager_state,
&merchant_id,
&event_id,
merchant_key_store,
)
.await
.attach_printable_lazy(|| format!("event not found for id: {}", &event_id))
.map_err(|error| {
logger::error!(?error);
error
})
.ok();
// Get status_code from webhook response
let status_code = updated_event.and_then(|updated_event| {
let webhook_response: Option<OutgoingWebhookResponseContent> =
updated_event.response.and_then(|res| {
res.peek()
.parse_struct("OutgoingWebhookResponseContent")
.map_err(|error| {
logger::error!(?error, "Error deserializing webhook response");
error
})
.ok()
});
webhook_response.and_then(|res| res.status_code)
});
let webhook_event = OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
merchant_id,
event_id,
event.event_type,
outgoing_webhook_event_content,
error,
event.initial_attempt_id,
status_code,
event.delivery_attempt,
);
state.event_handler().log_event(&webhook_event);
}
pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(
db: &dyn StorageInterface,
business_profile: &domain::Profile,
event: &domain::Event,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time(
db,
&business_profile.merchant_id,
0,
)
.await
.ok_or(errors::StorageError::ValueNotFound(
"Process tracker schedule time".into(), // Can raise a better error here
))
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let tracking_data = types::OutgoingWebhookTrackingData {
merchant_id: business_profile.merchant_id.clone(),
business_profile_id: business_profile.get_id().to_owned(),
event_type: event.event_type,
event_class: event.event_class,
primary_object_id: event.primary_object_id.clone(),
primary_object_type: event.primary_object_type,
initial_attempt_id: event.initial_attempt_id.clone(),
};
let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow;
let task = "OUTGOING_WEBHOOK_RETRY";
let tag = ["OUTGOING_WEBHOOKS"];
let process_tracker_id = scheduler::utils::get_process_tracker_id(
runner,
task,
&event.event_id,
&business_profile.merchant_id,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
let attributes = router_env::metric_attributes!(("flow", "OutgoingWebhookRetry"));
match db.insert_process(process_tracker_entry).await {
Ok(process_tracker) => {
crate::routes::metrics::TASKS_ADDED_COUNT.add(1, attributes);
Ok(process_tracker)
}
Err(error) => {
crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add(1, attributes);
Err(error)
}
}
}
fn get_webhook_url_from_business_profile(
business_profile: &domain::Profile,
) -> CustomResult<String, errors::WebhooksFlowError> {
let webhook_details = business_profile
.webhook_details
.clone()
.get_required_value("webhook_details")
.change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
webhook_details
.webhook_url
.get_required_value("webhook_url")
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured)
.map(ExposeInterface::expose)
}
pub(crate) fn get_outgoing_webhook_request(
merchant_context: &domain::MerchantContext,
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, String>>("HashMap<String,String>")
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked())),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, Secret::new(value.into_inner())))
.collect(),
})
}
match merchant_context
.get_merchant_account()
.get_compatible_connector()
{
#[cfg(feature = "stripe")]
Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::<
stripe_webhooks::StripeOutgoingWebhook,
>(outgoing_webhook, business_profile),
_ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
),
}
}
#[derive(Debug)]
enum ScheduleWebhookRetry {
WithProcessTracker(Box<storage::ProcessTracker>),
NoSchedule,
}
async fn update_event_if_client_error(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
error_message: String,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let is_webhook_notified = false;
let key_manager_state = &(&state).into();
let response_to_store = OutgoingWebhookResponseContent {
body: None,
headers: None,
status_code: None,
error_message: Some(error_message),
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: error_stack::Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
schedule_webhook_retry: ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
// Not including detailed error message in response information since it contains too
// much of diagnostic information to be exposed to the merchant.
update_event_if_client_error(
state.clone(),
merchant_key_store,
merchant_id,
event_id,
"Unable to send request to merchant server".to_string(),
)
.await?;
let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed);
logger::error!(
?error,
?delivery_attempt,
"An error occurred when sending webhook to merchant"
);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// Schedule a retry attempt for webhook delivery
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
*process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
}
Err(error)
}
async fn update_event_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
response: reqwest::Response,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let status_code = response.status();
let is_webhook_notified = status_code.is_success();
let key_manager_state = &(&state).into();
let response_headers = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
let response_to_store = OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
updated_event: domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful: true,
};
let initial_attempt_id = updated_event.initial_attempt_id.as_ref();
let delivery_attempt = updated_event.delivery_attempt;
if let Some((
initial_attempt_id,
enums::WebhookDeliveryAttempt::InitialAttempt
| enums::WebhookDeliveryAttempt::AutomaticRetry,
)) = initial_attempt_id.zip(delivery_attempt)
{
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to update initial delivery attempt")?;
}
Ok(())
}
fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {
metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
)
}
async fn success_response_handler(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
business_status: &'static str,
) -> CustomResult<(), errors::WebhooksFlowError> {
increment_webhook_outgoing_received_count(merchant_id);
match process_tracker {
Some(process_tracker) => state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
),
None => Ok(()),
}
}
async fn error_response_handler(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
schedule_webhook_retry: ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
logger::warn!(?error, ?delivery_attempt, status_code, %log_message);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// Schedule a retry attempt for webhook delivery
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
*process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
}
Err(error)
}
impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {
fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {
match content {
webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {
payment_id: payments_response.payment_id.clone(),
},
webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {
payment_id: refund_response.payment_id.clone(),
refund_id: refund_response.refund_id.clone(),
},
webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute {
payment_id: dispute_response.payment_id.clone(),
attempt_id: dispute_response.attempt_id.clone(),
dispute_id: dispute_response.dispute_id.clone(),
},
webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {
payment_method_id: mandate_response.payment_method_id.clone(),
mandate_id: mandate_response.mandate_id.clone(),
},
#[cfg(feature = "payouts")]
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
}
}
}
fn get_outgoing_webhook_event_content_from_event_metadata(
event_metadata: Option<storage::EventMetadata>,
) -> Option<OutgoingWebhookEventContent> {
event_metadata.map(|metadata| match metadata {
diesel_models::EventMetadata::Payment { payment_id } => {
OutgoingWebhookEventContent::Payment {
payment_id,
content: serde_json::Value::Null,
}
}
diesel_models::EventMetadata::Payout { payout_id } => OutgoingWebhookEventContent::Payout {
payout_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Refund {
payment_id,
refund_id,
} => OutgoingWebhookEventContent::Refund {
payment_id,
refund_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Dispute {
payment_id,
attempt_id,
dispute_id,
} => OutgoingWebhookEventContent::Dispute {
payment_id,
attempt_id,
dispute_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Mandate {
payment_method_id,
mandate_id,
} => OutgoingWebhookEventContent::Mandate {
payment_method_id,
mandate_id,
content: serde_json::Value::Null,
},
})
}
| {
"crate": "router",
"file": "crates/router/src/core/webhooks/outgoing.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_6709754090527951233 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/webhooks/webhook_events.rs
// Contains: 0 structs, 1 enums
use std::collections::HashSet;
use common_utils::{self, errors::CustomResult, fp_utils};
use error_stack::ResultExt;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use crate::{
core::errors::{self, RouterResponse, StorageErrorExt},
routes::SessionState,
services::ApplicationResponse,
types::{api, domain, storage, transformers::ForeignTryFrom},
utils::{OptionExt, StringExt},
};
const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100;
const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS: i64 = 90;
#[derive(Debug)]
enum MerchantAccountOrProfile {
MerchantAccount(Box<domain::MerchantAccount>),
Profile(Box<domain::Profile>),
}
#[instrument(skip(state))]
pub async fn list_initial_delivery_attempts(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
api_constraints: api::webhook_events::EventListConstraints,
) -> RouterResponse<api::webhook_events::TotalEventsResponse> {
let profile_id = api_constraints.profile_id.clone();
let constraints = api::webhook_events::EventListConstraintsInternal::foreign_try_from(
api_constraints.clone(),
)?;
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let (account, key_store) =
get_account_and_key_store(state.clone(), merchant_id.clone(), profile_id.clone()).await?;
let now = common_utils::date_time::now();
let events_list_begin_time =
(now.date() - time::Duration::days(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS)).midnight();
let (events, total_count) = match constraints {
api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => {
let events = match account {
MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
store
.list_initial_events_by_merchant_id_primary_object_id(
key_manager_state,
merchant_account.get_id(),
&object_id,
&key_store,
)
.await
}
MerchantAccountOrProfile::Profile(business_profile) => {
store
.list_initial_events_by_profile_id_primary_object_id(
key_manager_state,
business_profile.get_id(),
&object_id,
&key_store,
)
.await
}
}
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
let total_count = i64::try_from(events.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i64")?;
(events, total_count)
}
api_models::webhook_events::EventListConstraintsInternal::GenericFilter {
created_after,
created_before,
limit,
offset,
event_classes,
event_types,
is_delivered,
} => {
let limit = match limit {
Some(limit) if limit <= INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Ok(Some(limit)),
Some(limit) if limit > INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Err(
errors::ApiErrorResponse::InvalidRequestData{
message: format!("`limit` must be a number less than {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT}")
}
),
_ => Ok(Some(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT)),
}?;
let offset = match offset {
Some(offset) if offset > 0 => Some(offset),
_ => None,
};
let event_classes = event_classes.unwrap_or(HashSet::new());
let mut event_types = event_types.unwrap_or(HashSet::new());
if !event_classes.is_empty() {
event_types = finalize_event_types(event_classes, event_types).await?;
}
fp_utils::when(
!created_after
.zip(created_before)
.map(|(created_after, created_before)| created_after <= created_before)
.unwrap_or(true),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData { message: "The `created_after` timestamp must be an earlier timestamp compared to the `created_before` timestamp".to_string() })
},
)?;
let created_after = match created_after {
Some(created_after) => {
if created_after < events_list_begin_time {
Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_after` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") })
} else {
Ok(created_after)
}
}
None => Ok(events_list_begin_time),
}?;
let created_before = match created_before {
Some(created_before) => {
if created_before < events_list_begin_time {
Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_before` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") })
} else {
Ok(created_before)
}
}
None => Ok(now),
}?;
let events = match account {
MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
store
.list_initial_events_by_merchant_id_constraints(
key_manager_state,
merchant_account.get_id(),
created_after,
created_before,
limit,
offset,
event_types.clone(),
is_delivered,
&key_store,
)
.await
}
MerchantAccountOrProfile::Profile(business_profile) => {
store
.list_initial_events_by_profile_id_constraints(
key_manager_state,
business_profile.get_id(),
created_after,
created_before,
limit,
offset,
event_types.clone(),
is_delivered,
&key_store,
)
.await
}
}
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
let total_count = store
.count_initial_events_by_constraints(
&merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get total events count")?;
(events, total_count)
}
};
let events = events
.into_iter()
.map(api::webhook_events::EventListItemResponse::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(ApplicationResponse::Json(
api::webhook_events::TotalEventsResponse::new(total_count, events),
))
}
#[instrument(skip(state))]
pub async fn list_delivery_attempts(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
initial_attempt_id: String,
) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let events = store
.list_events_by_merchant_id_initial_attempt_id(
key_manager_state,
&merchant_id,
&initial_attempt_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list delivery attempts for initial event")?;
if events.is_empty() {
Err(error_stack::report!(
errors::ApiErrorResponse::EventNotFound
))
.attach_printable("No delivery attempts found with the specified `initial_attempt_id`")
} else {
Ok(ApplicationResponse::Json(
events
.into_iter()
.map(api::webhook_events::EventRetrieveResponse::try_from)
.collect::<Result<Vec<_>, _>>()?,
))
}
}
#[instrument(skip(state))]
#[cfg(feature = "v1")]
pub async fn retry_delivery_attempt(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
) -> RouterResponse<api::webhook_events::EventRetrieveResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let event_to_retry = store
.find_event_by_merchant_id_event_id(
key_manager_state,
&key_store.merchant_id,
&event_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
let business_profile_id = event_to_retry
.business_profile_id
.get_required_value("business_profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to read business profile ID from event to retry")?;
let business_profile = store
.find_business_profile_by_profile_id(key_manager_state, &key_store, &business_profile_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find business profile")?;
let delivery_attempt = storage::enums::WebhookDeliveryAttempt::ManualRetry;
let new_event_id = super::utils::generate_event_id();
let idempotent_event_id = super::utils::get_idempotent_event_id(
&event_to_retry.primary_object_id,
event_to_retry.event_type,
delivery_attempt,
)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let now = common_utils::date_time::now();
let new_event = domain::Event {
event_id: new_event_id.clone(),
event_type: event_to_retry.event_type,
event_class: event_to_retry.event_class,
is_webhook_notified: false,
primary_object_id: event_to_retry.primary_object_id,
primary_object_type: event_to_retry.primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: event_to_retry.primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id),
initial_attempt_id: event_to_retry.initial_attempt_id,
request: event_to_retry.request,
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: event_to_retry.metadata,
is_overall_delivery_successful: Some(false),
};
let event = store
.insert_event(key_manager_state, new_event, &key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert event")?;
// We only allow retrying deliveries for events with `request` populated.
let request_content = event
.request
.as_ref()
.get_required_value("request")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.peek()
.parse_struct("OutgoingWebhookRequestContent")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event request information")?;
Box::pin(super::outgoing::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
&key_store,
event,
request_content,
delivery_attempt,
None,
None,
))
.await;
let updated_event = store
.find_event_by_merchant_id_event_id(
key_manager_state,
&key_store.merchant_id,
&new_event_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
Ok(ApplicationResponse::Json(
api::webhook_events::EventRetrieveResponse::try_from(updated_event)?,
))
}
async fn get_account_and_key_store(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> errors::RouterResult<(MerchantAccountOrProfile, domain::MerchantKeyStore)> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
match profile_id {
// If profile ID is specified, return business profile, since a business profile is more
// specific than a merchant account.
Some(profile_id) => {
let business_profile = store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&merchant_key_store,
&merchant_id,
&profile_id,
)
.await
.attach_printable_lazy(|| {
format!(
"Failed to find business profile by merchant_id `{merchant_id:?}` and profile_id `{profile_id:?}`. \
The merchant_id associated with the business profile `{profile_id:?}` may be \
different than the merchant_id specified (`{merchant_id:?}`)."
)
})
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok((
MerchantAccountOrProfile::Profile(Box::new(business_profile)),
merchant_key_store,
))
}
None => {
let merchant_account = store
.find_merchant_account_by_merchant_id(
key_manager_state,
&merchant_id,
&merchant_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((
MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)),
merchant_key_store,
))
}
}
}
async fn finalize_event_types(
event_classes: HashSet<common_enums::EventClass>,
mut event_types: HashSet<common_enums::EventType>,
) -> CustomResult<HashSet<common_enums::EventType>, errors::ApiErrorResponse> {
// Examples:
// 1. event_classes = ["payments", "refunds"], event_types = ["payment_succeeded"]
// 2. event_classes = ["refunds"], event_types = ["payment_succeeded"]
// Create possible_event_types based on event_classes
// Example 1: possible_event_types = ["payment_*", "refund_*"]
// Example 2: possible_event_types = ["refund_*"]
let possible_event_types = event_classes
.clone()
.into_iter()
.flat_map(common_enums::EventClass::event_types)
.collect::<HashSet<_>>();
if event_types.is_empty() {
return Ok(possible_event_types);
}
// Extend event_types if disjoint with event_classes
// Example 1: event_types = ["payment_succeeded", "refund_*"], is_disjoint is used to extend "refund_*" and ignore "payment_*".
// Example 2: event_types = ["payment_succeeded", "refund_*"], is_disjoint is only used to extend "refund_*".
event_classes.into_iter().for_each(|class| {
let valid_event_types = class.event_types();
if event_types.is_disjoint(&valid_event_types) {
event_types.extend(valid_event_types);
}
});
// Validate event_types is a subset of possible_event_types
// Example 1: event_types is a subset of possible_event_types (valid)
// Example 2: event_types is not a subset of possible_event_types (error due to "payment_succeeded")
if !event_types.is_subset(&possible_event_types) {
return Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: "`event_types` must be a subset of `event_classes`".to_string(),
}
));
}
Ok(event_types.clone())
}
| {
"crate": "router",
"file": "crates/router/src/core/webhooks/webhook_events.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-712853406640956159 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/lock_utils.rs
// Contains: 0 structs, 1 enums
use router_env::Flow;
#[derive(Clone, Debug, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum ApiIdentifier {
Payments,
Refunds,
Webhooks,
Organization,
MerchantAccount,
MerchantConnector,
Configs,
Customers,
Ephemeral,
Health,
Mandates,
PaymentMethods,
PaymentMethodAuth,
Payouts,
Disputes,
CardsInfo,
Files,
Cache,
Profile,
Verification,
ApiKeys,
PaymentLink,
Routing,
Subscription,
Blocklist,
Forex,
RustLockerMigration,
Gsm,
Role,
User,
UserRole,
ConnectorOnboarding,
Recon,
AiWorkflow,
Poll,
ApplePayCertificatesMigration,
Relay,
Documentation,
CardNetworkTokenization,
Hypersense,
PaymentMethodSession,
ProcessTracker,
Authentication,
Proxy,
ProfileAcquirer,
ThreeDsDecisionRule,
GenericTokenization,
RecoveryRecovery,
}
impl From<Flow> for ApiIdentifier {
fn from(flow: Flow) -> Self {
match flow {
Flow::MerchantsAccountCreate
| Flow::MerchantsAccountRetrieve
| Flow::MerchantsAccountUpdate
| Flow::MerchantsAccountDelete
| Flow::MerchantTransferKey
| Flow::MerchantAccountList
| Flow::EnablePlatformAccount => Self::MerchantAccount,
Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => {
Self::Organization
}
Flow::RoutingCreateConfig
| Flow::RoutingLinkConfig
| Flow::RoutingUnlinkConfig
| Flow::RoutingRetrieveConfig
| Flow::RoutingRetrieveActiveConfig
| Flow::RoutingRetrieveDefaultConfig
| Flow::RoutingRetrieveDictionary
| Flow::RoutingUpdateConfig
| Flow::RoutingUpdateDefaultConfig
| Flow::RoutingDeleteConfig
| Flow::DecisionManagerDeleteConfig
| Flow::DecisionManagerRetrieveConfig
| Flow::ToggleDynamicRouting
| Flow::CreateDynamicRoutingConfig
| Flow::UpdateDynamicRoutingConfigs
| Flow::DecisionManagerUpsertConfig
| Flow::RoutingEvaluateRule
| Flow::DecisionEngineRuleMigration
| Flow::VolumeSplitOnRoutingType
| Flow::DecisionEngineDecideGatewayCall
| Flow::DecisionEngineGatewayFeedbackCall => Self::Routing,
Flow::CreateSubscription
| Flow::ConfirmSubscription
| Flow::CreateAndConfirmSubscription
| Flow::GetSubscription
| Flow::UpdateSubscription
| Flow::GetSubscriptionEstimate
| Flow::GetPlansForSubscription => Self::Subscription,
Flow::RetrieveForexFlow => Self::Forex,
Flow::AddToBlocklist => Self::Blocklist,
Flow::DeleteFromBlocklist => Self::Blocklist,
Flow::ListBlocklist => Self::Blocklist,
Flow::ToggleBlocklistGuard => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
| Flow::MerchantConnectorsUpdate
| Flow::MerchantConnectorsDelete
| Flow::MerchantConnectorsList => Self::MerchantConnector,
Flow::ConfigKeyCreate
| Flow::ConfigKeyFetch
| Flow::ConfigKeyUpdate
| Flow::ConfigKeyDelete
| Flow::CreateConfigKey => Self::Configs,
Flow::CustomersCreate
| Flow::CustomersRetrieve
| Flow::CustomersUpdate
| Flow::CustomersDelete
| Flow::CustomersGetMandates
| Flow::CustomersList
| Flow::CustomersListWithConstraints => Self::Customers,
Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,
Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health,
Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates,
Flow::PaymentMethodsCreate
| Flow::PaymentMethodsMigrate
| Flow::PaymentMethodsBatchUpdate
| Flow::PaymentMethodsList
| Flow::CustomerPaymentMethodsList
| Flow::GetPaymentMethodTokenData
| Flow::PaymentMethodsRetrieve
| Flow::PaymentMethodsUpdate
| Flow::PaymentMethodsDelete
| Flow::NetworkTokenStatusCheck
| Flow::PaymentMethodCollectLink
| Flow::ValidatePaymentMethod
| Flow::ListCountriesCurrencies
| Flow::DefaultPaymentMethodsSet
| Flow::PaymentMethodSave
| Flow::TotalPaymentMethodCount => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
Flow::PaymentsCreate
| Flow::PaymentsRetrieve
| Flow::PaymentsRetrieveForceSync
| Flow::PaymentsUpdate
| Flow::PaymentsConfirm
| Flow::PaymentsCapture
| Flow::PaymentsCancel
| Flow::PaymentsCancelPostCapture
| Flow::PaymentsApprove
| Flow::PaymentsReject
| Flow::PaymentsSessionToken
| Flow::PaymentsStart
| Flow::PaymentsList
| Flow::PaymentsFilters
| Flow::PaymentsAggregate
| Flow::PaymentsRedirect
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExtendAuthorization
| Flow::PaymentsExternalAuthentication
| Flow::PaymentsAuthorize
| Flow::GetExtendedCardInfo
| Flow::PaymentsCompleteAuthorize
| Flow::PaymentsManualUpdate
| Flow::SessionUpdateTaxCalculation
| Flow::PaymentsConfirmIntent
| Flow::PaymentsCreateIntent
| Flow::PaymentsGetIntent
| Flow::GiftCardBalanceCheck
| Flow::PaymentsPostSessionTokens
| Flow::PaymentsUpdateMetadata
| Flow::PaymentsUpdateIntent
| Flow::PaymentsCreateAndConfirmIntent
| Flow::PaymentStartRedirection
| Flow::ProxyConfirmIntent
| Flow::PaymentsRetrieveUsingMerchantReferenceId
| Flow::PaymentAttemptsList
| Flow::RecoveryPaymentsCreate
| Flow::PaymentsSubmitEligibility => Self::Payments,
Flow::PayoutsCreate
| Flow::PayoutsRetrieve
| Flow::PayoutsUpdate
| Flow::PayoutsCancel
| Flow::PayoutsFulfill
| Flow::PayoutsList
| Flow::PayoutsFilter
| Flow::PayoutsAccounts
| Flow::PayoutsConfirm
| Flow::PayoutLinkInitiate => Self::Payouts,
Flow::RefundsCreate
| Flow::RefundsRetrieve
| Flow::RefundsRetrieveForceSync
| Flow::RefundsUpdate
| Flow::RefundsList
| Flow::RefundsFilters
| Flow::RefundsAggregate
| Flow::RefundsManualUpdate => Self::Refunds,
Flow::Relay | Flow::RelayRetrieve => Self::Relay,
Flow::FrmFulfillment
| Flow::IncomingWebhookReceive
| Flow::IncomingRelayWebhookReceive
| Flow::WebhookEventInitialDeliveryAttemptList
| Flow::WebhookEventDeliveryAttemptList
| Flow::WebhookEventDeliveryRetry
| Flow::RecoveryIncomingWebhookReceive
| Flow::IncomingNetworkTokenWebhookReceive => Self::Webhooks,
Flow::ApiKeyCreate
| Flow::ApiKeyRetrieve
| Flow::ApiKeyUpdate
| Flow::ApiKeyRevoke
| Flow::ApiKeyList => Self::ApiKeys,
Flow::DisputesRetrieve
| Flow::DisputesList
| Flow::DisputesFilters
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
| Flow::RetrieveDisputeEvidence
| Flow::DisputesAggregate
| Flow::DeleteDisputeEvidence => Self::Disputes,
Flow::CardsInfo
| Flow::CardsInfoCreate
| Flow::CardsInfoUpdate
| Flow::CardsInfoMigrate => Self::CardsInfo,
Flow::CreateFile | Flow::DeleteFile | Flow::RetrieveFile => Self::Files,
Flow::CacheInvalidate => Self::Cache,
Flow::ProfileCreate
| Flow::ProfileUpdate
| Flow::ProfileRetrieve
| Flow::ProfileDelete
| Flow::ProfileList
| Flow::ToggleExtendedCardInfo
| Flow::ToggleConnectorAgnosticMit => Self::Profile,
Flow::PaymentLinkRetrieve
| Flow::PaymentLinkInitiate
| Flow::PaymentSecureLinkInitiate
| Flow::PaymentLinkList
| Flow::PaymentLinkStatus => Self::PaymentLink,
Flow::Verification => Self::Verification,
Flow::RustLockerMigration => Self::RustLockerMigration,
Flow::GsmRuleCreate
| Flow::GsmRuleRetrieve
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,
Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration,
Flow::UserConnectAccount
| Flow::UserSignUp
| Flow::UserSignIn
| Flow::Signout
| Flow::ChangePassword
| Flow::SetDashboardMetadata
| Flow::GetMultipleDashboardMetadata
| Flow::VerifyPaymentConnector
| Flow::InternalUserSignup
| Flow::TenantUserCreate
| Flow::SwitchOrg
| Flow::SwitchMerchantV2
| Flow::SwitchProfile
| Flow::CreatePlatformAccount
| Flow::UserOrgMerchantCreate
| Flow::UserMerchantAccountCreate
| Flow::GenerateSampleData
| Flow::DeleteSampleData
| Flow::GetUserDetails
| Flow::GetUserRoleDetails
| Flow::ForgotPassword
| Flow::ResetPassword
| Flow::RotatePassword
| Flow::InviteMultipleUser
| Flow::ReInviteUser
| Flow::UserSignUpWithMerchantId
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
| Flow::TotpReset
| Flow::TotpVerify
| Flow::TotpUpdate
| Flow::RecoveryCodeVerify
| Flow::RecoveryCodesGenerate
| Flow::TerminateTwoFactorAuth
| Flow::TwoFactorAuthStatus
| Flow::CreateUserAuthenticationMethod
| Flow::UpdateUserAuthenticationMethod
| Flow::ListUserAuthenticationMethods
| Flow::UserTransferKey
| Flow::GetSsoAuthUrl
| Flow::SignInWithSso
| Flow::ListOrgForUser
| Flow::ListMerchantsForUserInOrg
| Flow::ListProfileForUserInOrgAndMerchant
| Flow::ListInvitationsForUser
| Flow::AuthSelect
| Flow::GetThemeUsingLineage
| Flow::GetThemeUsingThemeId
| Flow::UploadFileToThemeStorage
| Flow::CreateTheme
| Flow::UpdateTheme
| Flow::DeleteTheme
| Flow::CreateUserTheme
| Flow::UpdateUserTheme
| Flow::DeleteUserTheme
| Flow::GetUserThemeUsingThemeId
| Flow::UploadFileToUserThemeStorage
| Flow::GetUserThemeUsingLineage
| Flow::ListAllThemesInLineage
| Flow::CloneConnector => Self::User,
Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow,
Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
| Flow::GetRoleV2
| Flow::GetRoleFromToken
| Flow::GetRoleFromTokenV2
| Flow::GetParentGroupsInfoForRoleFromToken
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
| Flow::GetParentGroupInfo
| Flow::AcceptInvitationsV2
| Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
| Flow::CreateRole
| Flow::CreateRoleV2
| Flow::UpdateRole
| Flow::UserFromEmail
| Flow::ListUsersInLineage => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
}
Flow::ReconMerchantUpdate
| Flow::ReconTokenRequest
| Flow::ReconServiceRequest
| Flow::ReconVerifyToken => Self::Recon,
Flow::RetrievePollStatus => Self::Poll,
Flow::FeatureMatrix => Self::Documentation,
Flow::TokenizeCard
| Flow::TokenizeCardUsingPaymentMethodId
| Flow::TokenizeCardBatch => Self::CardNetworkTokenization,
Flow::HypersenseTokenRequest
| Flow::HypersenseVerifyToken
| Flow::HypersenseSignoutToken => Self::Hypersense,
Flow::PaymentMethodSessionCreate
| Flow::PaymentMethodSessionRetrieve
| Flow::PaymentMethodSessionConfirm
| Flow::PaymentMethodSessionUpdateSavedPaymentMethod
| Flow::PaymentMethodSessionDeleteSavedPaymentMethod
| Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession,
Flow::RevenueRecoveryRetrieve | Flow::RevenueRecoveryResume => Self::ProcessTracker,
Flow::AuthenticationCreate
| Flow::AuthenticationEligibility
| Flow::AuthenticationSync
| Flow::AuthenticationSyncPostUpdate
| Flow::AuthenticationAuthenticate => Self::Authentication,
Flow::Proxy => Self::Proxy,
Flow::ProfileAcquirerCreate | Flow::ProfileAcquirerUpdate => Self::ProfileAcquirer,
Flow::ThreeDsDecisionRuleExecute => Self::ThreeDsDecisionRule,
Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => {
Self::GenericTokenization
}
Flow::RecoveryDataBackfill | Flow::RevenueRecoveryRedis => Self::RecoveryRecovery,
}
}
}
| {
"crate": "router",
"file": "crates/router/src/routes/lock_utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-5350622188072912632 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/dummy_connector/errors.rs
// Contains: 0 structs, 1 enums
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
ServerNotAvailable,
ObjectNotFound,
InvalidRequestError,
}
#[derive(Debug, Clone, router_derive::ApiError)]
#[error(error_type_enum = ErrorType)]
// TODO: Remove this line if InternalServerError is used anywhere
#[allow(dead_code)]
pub enum DummyConnectorErrors {
#[error(error_type = ErrorType::ServerNotAvailable, code = "DC_00", message = "Something went wrong")]
InternalServerError,
#[error(error_type = ErrorType::ObjectNotFound, code = "DC_01", message = "Payment does not exist in our records")]
PaymentNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_02", message = "Missing required param: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_03", message = "The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_04", message = "Card not supported. Please use test cards")]
CardNotSupported,
#[error(error_type = ErrorType::ObjectNotFound, code = "DC_05", message = "Refund does not exist in our records")]
RefundNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_06", message = "Payment is not successful")]
PaymentNotSuccessful,
#[error(error_type = ErrorType::ServerNotAvailable, code = "DC_07", message = "Error occurred while storing the payment")]
PaymentStoringError,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_08", message = "Payment declined: {message}")]
PaymentDeclined { message: &'static str },
}
impl core::fmt::Display for DummyConnectorErrors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(self)
.unwrap_or_else(|_| "Dummy connector error response".to_string())
)
}
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>
for DummyConnectorErrors
{
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None))
}
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("DC", 1, self.error_message(), None))
}
Self::MissingRequiredField { field_name: _ } => {
AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None))
}
Self::RefundAmountExceedsPaymentAmount => {
AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None))
}
Self::CardNotSupported => {
AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None))
}
Self::RefundNotFound => {
AER::NotFound(ApiError::new("DC", 5, self.error_message(), None))
}
Self::PaymentNotSuccessful => {
AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None))
}
Self::PaymentStoringError => {
AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None))
}
Self::PaymentDeclined { message: _ } => {
AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None))
}
}
}
}
| {
"crate": "router",
"file": "crates/router/src/routes/dummy_connector/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
diesel_file_-8785310203052131258 | clm | file | // Repository: hyperswitch
// Crate: diesel_models
// File: crates/diesel_models/src/schema_v2.rs
// Contains: 50 table schemas, 0 diesel enums
// @generated automatically by Diesel CLI.
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
address (address_id) {
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
city -> Nullable<Varchar>,
country -> Nullable<CountryAlpha2>,
line1 -> Nullable<Bytea>,
line2 -> Nullable<Bytea>,
line3 -> Nullable<Bytea>,
state -> Nullable<Bytea>,
zip -> Nullable<Bytea>,
first_name -> Nullable<Bytea>,
last_name -> Nullable<Bytea>,
phone_number -> Nullable<Bytea>,
#[max_length = 8]
country_code -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
email -> Nullable<Bytea>,
origin_zip -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
api_keys (key_id) {
#[max_length = 64]
key_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
#[max_length = 128]
hashed_api_key -> Varchar,
#[max_length = 16]
prefix -> Varchar,
created_at -> Timestamp,
expires_at -> Nullable<Timestamp>,
last_used -> Nullable<Timestamp>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
authentication (authentication_id) {
#[max_length = 64]
authentication_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
connector_authentication_id -> Nullable<Varchar>,
authentication_data -> Nullable<Jsonb>,
#[max_length = 64]
payment_method_id -> Varchar,
#[max_length = 64]
authentication_type -> Nullable<Varchar>,
#[max_length = 64]
authentication_status -> Varchar,
#[max_length = 64]
authentication_lifecycle_status -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
maximum_supported_version -> Nullable<Jsonb>,
#[max_length = 64]
threeds_server_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
cavv -> Nullable<Varchar>,
#[max_length = 64]
authentication_flow_type -> Nullable<Varchar>,
message_version -> Nullable<Jsonb>,
#[max_length = 64]
eci -> Nullable<Varchar>,
#[max_length = 64]
trans_status -> Nullable<Varchar>,
#[max_length = 64]
acquirer_bin -> Nullable<Varchar>,
#[max_length = 64]
acquirer_merchant_id -> Nullable<Varchar>,
three_ds_method_data -> Nullable<Varchar>,
three_ds_method_url -> Nullable<Varchar>,
acs_url -> Nullable<Varchar>,
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 255]
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
#[max_length = 64]
acquirer_country_code -> Nullable<Varchar>,
service_details -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 128]
authentication_client_secret -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
#[max_length = 2048]
return_url -> Nullable<Varchar>,
amount -> Nullable<Int8>,
currency -> Nullable<Currency>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
browser_info -> Nullable<Jsonb>,
email -> Nullable<Bytea>,
#[max_length = 128]
profile_acquirer_id -> Nullable<Varchar>,
challenge_code -> Nullable<Varchar>,
challenge_cancel -> Nullable<Varchar>,
challenge_code_reason -> Nullable<Varchar>,
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_fingerprint (id) {
id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
encrypted_fingerprint -> Text,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_lookup (id) {
id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
fingerprint -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
business_profile (id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_name -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
return_url -> Nullable<Text>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
payout_link_config -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
always_request_extended_authorization -> Nullable<Bool>,
is_click_to_pay_enabled -> Bool,
authentication_product_ids -> Nullable<Jsonb>,
card_testing_guard_config -> Nullable<Jsonb>,
card_testing_secret_key -> Nullable<Bytea>,
is_clear_pan_retries_enabled -> Bool,
force_3ds_challenge -> Nullable<Bool>,
is_debit_routing_enabled -> Bool,
merchant_business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
id -> Varchar,
is_iframe_redirection_enabled -> Nullable<Bool>,
three_ds_decision_rule_algorithm -> Nullable<Jsonb>,
acquirer_config_map -> Nullable<Jsonb>,
#[max_length = 16]
merchant_category_code -> Nullable<Varchar>,
#[max_length = 32]
merchant_country_code -> Nullable<Varchar>,
dispute_polling_interval -> Nullable<Int4>,
is_manual_retry_enabled -> Nullable<Bool>,
always_enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
billing_processor_id -> Nullable<Varchar>,
is_external_vault_enabled -> Nullable<Bool>,
external_vault_connector_details -> Nullable<Jsonb>,
is_l2_l3_enabled -> Nullable<Bool>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
order_fulfillment_time -> Nullable<Int8>,
order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>,
#[max_length = 64]
frm_routing_algorithm_id -> Nullable<Varchar>,
#[max_length = 64]
payout_routing_algorithm_id -> Nullable<Varchar>,
default_fallback_routing -> Nullable<Jsonb>,
three_ds_decision_manager_config -> Nullable<Jsonb>,
should_collect_cvv_during_payment -> Nullable<Bool>,
revenue_recovery_retry_algorithm_type -> Nullable<RevenueRecoveryAlgorithmType>,
revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>,
#[max_length = 16]
split_txns_enabled -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
callback_mapper (id, type_) {
#[max_length = 128]
id -> Varchar,
#[sql_name = "type"]
#[max_length = 64]
type_ -> Varchar,
data -> Jsonb,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
captures (capture_id) {
#[max_length = 64]
capture_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> CaptureStatus,
amount -> Int8,
currency -> Nullable<Currency>,
#[max_length = 255]
connector -> Varchar,
#[max_length = 255]
error_message -> Nullable<Varchar>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 255]
error_reason -> Nullable<Varchar>,
tax_amount -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
authorized_attempt_id -> Varchar,
#[max_length = 128]
connector_capture_id -> Nullable<Varchar>,
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
processor_capture_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
cards_info (card_iin) {
#[max_length = 16]
card_iin -> Varchar,
card_issuer -> Nullable<Text>,
card_network -> Nullable<Text>,
card_type -> Nullable<Text>,
card_subtype -> Nullable<Text>,
card_issuing_country -> Nullable<Text>,
#[max_length = 32]
bank_code_id -> Nullable<Varchar>,
#[max_length = 32]
bank_code -> Nullable<Varchar>,
#[max_length = 32]
country_code -> Nullable<Varchar>,
date_created -> Timestamp,
last_updated -> Nullable<Timestamp>,
last_updated_provider -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
configs (key) {
id -> Int4,
#[max_length = 255]
key -> Varchar,
config -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
customers (id) {
#[max_length = 64]
merchant_id -> Varchar,
name -> Nullable<Bytea>,
email -> Nullable<Bytea>,
phone -> Nullable<Bytea>,
#[max_length = 8]
phone_country_code -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
created_at -> Timestamp,
metadata -> Nullable<Json>,
connector_customer -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
default_payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
tax_registration_id -> Nullable<Bytea>,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
default_billing_address -> Nullable<Bytea>,
default_shipping_address -> Nullable<Bytea>,
status -> Nullable<DeleteStatus>,
#[max_length = 64]
id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dashboard_metadata (id) {
id -> Int4,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
org_id -> Varchar,
data_key -> DashboardMetadata,
data_value -> Json,
#[max_length = 64]
created_by -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
amount -> Varchar,
#[max_length = 255]
currency -> Varchar,
dispute_stage -> DisputeStage,
dispute_status -> DisputeStatus,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
connector_status -> Varchar,
#[max_length = 255]
connector_dispute_id -> Varchar,
#[max_length = 255]
connector_reason -> Nullable<Varchar>,
#[max_length = 255]
connector_reason_code -> Nullable<Varchar>,
challenge_required_by -> Nullable<Timestamp>,
connector_created_at -> Nullable<Timestamp>,
connector_updated_at -> Nullable<Timestamp>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
connector -> Varchar,
evidence -> Jsonb,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
#[max_length = 32]
organization_id -> Varchar,
dispute_currency -> Nullable<Currency>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dynamic_routing_stats (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
amount -> Int8,
#[max_length = 64]
success_based_routing_connector -> Varchar,
#[max_length = 64]
payment_connector -> Varchar,
currency -> Nullable<Currency>,
#[max_length = 64]
payment_method -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
payment_status -> AttemptStatus,
conclusive_classification -> SuccessBasedRoutingConclusiveState,
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 64]
global_success_based_connector -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
event_type -> EventType,
event_class -> EventClass,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
primary_object_type -> EventObjectType,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
business_profile_id -> Nullable<Varchar>,
primary_object_created_at -> Nullable<Timestamp>,
#[max_length = 64]
idempotent_event_id -> Nullable<Varchar>,
#[max_length = 64]
initial_attempt_id -> Nullable<Varchar>,
request -> Nullable<Bytea>,
response -> Nullable<Bytea>,
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
file_metadata (file_id, merchant_id) {
#[max_length = 64]
file_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
file_name -> Nullable<Varchar>,
file_size -> Int4,
#[max_length = 255]
file_type -> Varchar,
#[max_length = 255]
provider_file_id -> Nullable<Varchar>,
#[max_length = 255]
file_upload_provider -> Nullable<Varchar>,
available -> Bool,
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
created_at -> Timestamp,
#[max_length = 255]
frm_name -> Varchar,
#[max_length = 255]
frm_transaction_id -> Nullable<Varchar>,
frm_transaction_type -> FraudCheckType,
frm_status -> FraudCheckStatus,
frm_score -> Nullable<Int4>,
frm_reason -> Nullable<Jsonb>,
#[max_length = 255]
frm_error -> Nullable<Varchar>,
payment_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
payment_capture_method -> Nullable<CaptureMethod>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
gateway_status_map (connector, flow, sub_flow, code, message) {
#[max_length = 64]
connector -> Varchar,
#[max_length = 64]
flow -> Varchar,
#[max_length = 64]
sub_flow -> Varchar,
#[max_length = 255]
code -> Varchar,
#[max_length = 1024]
message -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 64]
router_error -> Nullable<Varchar>,
#[max_length = 64]
decision -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
step_up_possible -> Bool,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
#[max_length = 64]
error_category -> Nullable<Varchar>,
clear_pan_possible -> Bool,
feature_data -> Nullable<Jsonb>,
#[max_length = 64]
feature -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
generic_link (link_id) {
#[max_length = 64]
link_id -> Varchar,
#[max_length = 64]
primary_reference -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
expiry -> Timestamp,
link_data -> Jsonb,
link_status -> Jsonb,
link_type -> GenericLinkType,
url -> Text,
return_url -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction_default (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
incremental_authorization (authorization_id, merchant_id) {
#[max_length = 64]
authorization_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
amount -> Int8,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
#[max_length = 64]
connector_authorization_id -> Nullable<Varchar>,
previously_authorized_amount -> Int8,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
invoice (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
subscription_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_connector_id -> Varchar,
#[max_length = 64]
payment_intent_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
customer_id -> Varchar,
amount -> Int8,
#[max_length = 3]
currency -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 128]
provider_name -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
connector_invoice_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
locker_mock_up (id) {
id -> Int4,
#[max_length = 255]
card_id -> Varchar,
#[max_length = 255]
external_id -> Varchar,
#[max_length = 255]
card_fingerprint -> Varchar,
#[max_length = 255]
card_global_fingerprint -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
card_number -> Varchar,
#[max_length = 255]
card_exp_year -> Varchar,
#[max_length = 255]
card_exp_month -> Varchar,
#[max_length = 255]
name_on_card -> Nullable<Varchar>,
#[max_length = 255]
nickname -> Nullable<Varchar>,
#[max_length = 255]
customer_id -> Nullable<Varchar>,
duplicate -> Nullable<Bool>,
#[max_length = 8]
card_cvc -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
enc_card_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
mandate_status -> MandateStatus,
mandate_type -> MandateType,
customer_accepted_at -> Nullable<Timestamp>,
#[max_length = 64]
customer_ip_address -> Nullable<Varchar>,
#[max_length = 255]
customer_user_agent -> Nullable<Varchar>,
#[max_length = 128]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
previous_attempt_id -> Nullable<Varchar>,
created_at -> Timestamp,
mandate_amount -> Nullable<Int8>,
mandate_currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_mandate_id -> Nullable<Varchar>,
start_date -> Nullable<Timestamp>,
end_date -> Nullable<Timestamp>,
metadata -> Nullable<Jsonb>,
connector_mandate_ids -> Nullable<Jsonb>,
#[max_length = 64]
original_payment_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
#[max_length = 2048]
customer_user_agent_extended -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_account (id) {
merchant_name -> Nullable<Bytea>,
merchant_details -> Nullable<Bytea>,
#[max_length = 128]
publishable_key -> Nullable<Varchar>,
storage_scheme -> MerchantStorageScheme,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
organization_id -> Varchar,
recon_status -> ReconStatus,
version -> ApiVersion,
is_platform_account -> Bool,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
product_type -> Nullable<Varchar>,
#[max_length = 64]
merchant_account_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_connector_account (id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
connector_name -> Varchar,
connector_account_details -> Bytea,
disabled -> Nullable<Bool>,
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
connector_webhook_details -> Nullable<Jsonb>,
frm_config -> Nullable<Array<Nullable<Jsonb>>>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
version -> ApiVersion,
#[max_length = 64]
id -> Varchar,
feature_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_key_store (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
organization (id) {
organization_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
id -> Varchar,
organization_name -> Nullable<Text>,
version -> ApiVersion,
#[max_length = 64]
organization_type -> Nullable<Varchar>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_attempt (id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> AttemptStatus,
#[max_length = 64]
connector -> Nullable<Varchar>,
error_message -> Nullable<Text>,
surcharge_amount -> Nullable<Int8>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
authentication_type -> Nullable<AuthenticationType>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
#[max_length = 255]
cancellation_reason -> Nullable<Varchar>,
amount_to_capture -> Nullable<Int8>,
browser_info -> Nullable<Jsonb>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 128]
payment_token -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
#[max_length = 50]
payment_experience -> Nullable<Varchar>,
payment_method_data -> Nullable<Jsonb>,
preprocessing_step_id -> Nullable<Varchar>,
error_reason -> Nullable<Text>,
multiple_capture_count -> Nullable<Int2>,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
amount_capturable -> Int8,
#[max_length = 32]
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
encoded_data -> Nullable<Text>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
net_amount -> Nullable<Int8>,
external_three_ds_authentication_attempted -> Nullable<Bool>,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
authentication_id -> Nullable<Varchar>,
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
client_source -> Nullable<Varchar>,
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 32]
card_network -> Nullable<Varchar>,
shipping_cost -> Nullable<Int8>,
order_tax_amount -> Nullable<Int8>,
request_extended_authorization -> Nullable<Bool>,
extended_authorization_applied -> Nullable<Bool>,
capture_before -> Nullable<Timestamp>,
card_discovery -> Nullable<CardDiscovery>,
charges -> Nullable<Jsonb>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
#[max_length = 255]
connector_request_reference_id -> Nullable<Varchar>,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
is_overcapture_enabled -> Nullable<Bool>,
network_details -> Nullable<Jsonb>,
is_stored_credential -> Nullable<Bool>,
authorized_amount -> Nullable<Int8>,
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 128]
connector_payment_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_subtype -> Varchar,
routing_result -> Nullable<Jsonb>,
authentication_applied -> Nullable<AuthenticationType>,
#[max_length = 128]
external_reference_id -> Nullable<Varchar>,
tax_on_surcharge -> Nullable<Int8>,
payment_method_billing_address -> Nullable<Bytea>,
redirection_data -> Nullable<Jsonb>,
connector_payment_data -> Nullable<Text>,
connector_token_details -> Nullable<Jsonb>,
#[max_length = 64]
id -> Varchar,
feature_metadata -> Nullable<Jsonb>,
#[max_length = 32]
network_advice_code -> Nullable<Varchar>,
#[max_length = 32]
network_decline_code -> Nullable<Varchar>,
network_error_message -> Nullable<Text>,
#[max_length = 64]
attempts_group_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_intent (id) {
#[max_length = 64]
merchant_id -> Varchar,
status -> IntentStatus,
amount -> Int8,
currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 255]
return_url -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
setup_future_usage -> Nullable<FutureUsage>,
#[max_length = 64]
active_attempt_id -> Nullable<Varchar>,
order_details -> Nullable<Array<Nullable<Jsonb>>>,
allowed_payment_method_types -> Nullable<Json>,
connector_metadata -> Nullable<Json>,
feature_metadata -> Nullable<Json>,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 255]
payment_link_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
surcharge_applicable -> Nullable<Bool>,
request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>,
authorization_count -> Nullable<Int4>,
session_expiry -> Nullable<Timestamp>,
request_external_three_ds_authentication -> Nullable<Bool>,
frm_metadata -> Nullable<Jsonb>,
customer_details -> Nullable<Bytea>,
shipping_cost -> Nullable<Int8>,
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
skip_external_tax_calculation -> Nullable<Bool>,
request_extended_authorization -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
split_payments -> Nullable<Jsonb>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
force_3ds_challenge_trigger -> Nullable<Bool>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
is_payment_id_from_merchant -> Nullable<Bool>,
#[max_length = 64]
payment_channel -> Nullable<Varchar>,
tax_status -> Nullable<Varchar>,
discount_amount -> Nullable<Int8>,
shipping_amount_tax -> Nullable<Int8>,
duty_amount -> Nullable<Int8>,
order_date -> Nullable<Timestamp>,
enable_partial_authorization -> Nullable<Bool>,
enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
mit_category -> Nullable<Varchar>,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
prerouting_algorithm -> Nullable<Jsonb>,
surcharge_amount -> Nullable<Int8>,
tax_on_surcharge -> Nullable<Int8>,
#[max_length = 64]
frm_merchant_decision -> Nullable<Varchar>,
#[max_length = 255]
statement_descriptor -> Nullable<Varchar>,
enable_payment_link -> Nullable<Bool>,
apply_mit_exemption -> Nullable<Bool>,
customer_present -> Nullable<Bool>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
payment_link_config -> Nullable<Jsonb>,
#[max_length = 64]
id -> Varchar,
#[max_length = 16]
split_txns_enabled -> Nullable<Varchar>,
#[max_length = 64]
active_attempts_group_id -> Nullable<Varchar>,
#[max_length = 16]
active_attempt_id_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_link (payment_link_id) {
#[max_length = 255]
payment_link_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 255]
link_to_pay -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
amount -> Int8,
currency -> Nullable<Currency>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
fulfilment_time -> Nullable<Timestamp>,
#[max_length = 64]
custom_merchant_name -> Nullable<Varchar>,
payment_link_config -> Nullable<Jsonb>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 255]
secure_link -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_methods (id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
last_used_at -> Timestamp,
connector_mandate_details -> Nullable<Jsonb>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
payment_method_billing_address -> Nullable<Bytea>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
#[max_length = 128]
network_token_requestor_reference_id -> Nullable<Varchar>,
#[max_length = 64]
network_token_locker_id -> Nullable<Varchar>,
network_token_payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
external_vault_source -> Nullable<Varchar>,
#[max_length = 64]
vault_type -> Nullable<Varchar>,
#[max_length = 64]
locker_fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 64]
payment_method_subtype -> Nullable<Varchar>,
#[max_length = 64]
id -> Varchar,
external_vault_token_data -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payout_attempt (merchant_id, payout_attempt_id) {
#[max_length = 64]
payout_attempt_id -> Varchar,
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
connector -> Nullable<Varchar>,
#[max_length = 128]
connector_payout_id -> Nullable<Varchar>,
#[max_length = 64]
payout_token -> Nullable<Varchar>,
status -> PayoutStatus,
is_eligible -> Nullable<Bool>,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
business_label -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
routing_info -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
additional_payout_method_data -> Nullable<Jsonb>,
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
payout_connector_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payouts (merchant_id, payout_id) {
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
address_id -> Nullable<Varchar>,
payout_type -> Nullable<PayoutType>,
#[max_length = 64]
payout_method_id -> Nullable<Varchar>,
amount -> Int8,
destination_currency -> Currency,
source_currency -> Currency,
#[max_length = 255]
description -> Nullable<Varchar>,
recurring -> Bool,
auto_fulfill -> Bool,
#[max_length = 255]
return_url -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Varchar,
status -> PayoutStatus,
confirm -> Nullable<Bool>,
#[max_length = 255]
payout_link_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 32]
priority -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
process_tracker (id) {
#[max_length = 127]
id -> Varchar,
#[max_length = 64]
name -> Nullable<Varchar>,
tag -> Array<Nullable<Text>>,
#[max_length = 64]
runner -> Nullable<Varchar>,
retry_count -> Int4,
schedule_time -> Nullable<Timestamp>,
#[max_length = 255]
rule -> Varchar,
tracking_data -> Json,
#[max_length = 255]
business_status -> Varchar,
status -> ProcessTrackerStatus,
event -> Array<Nullable<Text>>,
created_at -> Timestamp,
updated_at -> Timestamp,
version -> ApiVersion,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
refund (id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 128]
connector_transaction_id -> Varchar,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_refund_id -> Nullable<Varchar>,
#[max_length = 64]
external_reference_id -> Nullable<Varchar>,
refund_type -> RefundType,
total_amount -> Int8,
currency -> Currency,
refund_amount -> Int8,
refund_status -> RefundStatus,
sent_to_gateway -> Bool,
refund_error_message -> Nullable<Text>,
metadata -> Nullable<Json>,
#[max_length = 128]
refund_arn -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
refund_reason -> Nullable<Varchar>,
refund_error_code -> Nullable<Text>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
charges -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
split_refunds -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
processor_refund_data -> Nullable<Text>,
processor_transaction_data -> Nullable<Text>,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
#[max_length = 64]
connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
relay (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
connector_resource_id -> Varchar,
#[max_length = 64]
connector_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
relay_type -> RelayType,
request_data -> Nullable<Jsonb>,
status -> RelayStatus,
#[max_length = 128]
connector_reference_id -> Nullable<Varchar>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
created_at -> Timestamp,
modified_at -> Timestamp,
response_data -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
reverse_lookup (lookup_id) {
#[max_length = 128]
lookup_id -> Varchar,
#[max_length = 128]
sk_id -> Varchar,
#[max_length = 128]
pk_id -> Varchar,
#[max_length = 128]
source -> Varchar,
#[max_length = 32]
updated_by -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
roles (role_id) {
#[max_length = 64]
role_name -> Varchar,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Varchar,
groups -> Array<Nullable<Text>>,
scope -> RoleScope,
created_at -> Timestamp,
#[max_length = 64]
created_by -> Varchar,
last_modified_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
routing_algorithm (algorithm_id) {
#[max_length = 64]
algorithm_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
kind -> RoutingAlgorithmKind,
algorithm_data -> Jsonb,
created_at -> Timestamp,
modified_at -> Timestamp,
algorithm_for -> TransactionType,
#[max_length = 64]
decision_engine_routing_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
subscription (id) {
#[max_length = 128]
id -> Varchar,
#[max_length = 128]
status -> Varchar,
#[max_length = 128]
billing_processor -> Nullable<Varchar>,
#[max_length = 128]
payment_method_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 128]
connector_subscription_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_reference_id -> Nullable<Varchar>,
#[max_length = 128]
plan_id -> Nullable<Varchar>,
#[max_length = 128]
item_price_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
themes (theme_id) {
#[max_length = 64]
theme_id -> Varchar,
#[max_length = 64]
tenant_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
theme_name -> Varchar,
#[max_length = 64]
email_primary_color -> Varchar,
#[max_length = 64]
email_foreground_color -> Varchar,
#[max_length = 64]
email_background_color -> Varchar,
#[max_length = 64]
email_entity_name -> Varchar,
email_entity_logo_url -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
tokenization (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
created_at -> Timestamp,
updated_at -> Timestamp,
#[max_length = 255]
locker_id -> Varchar,
flag -> TokenizationFlag,
version -> ApiVersion,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
unified_translations (unified_code, unified_message, locale) {
#[max_length = 255]
unified_code -> Varchar,
#[max_length = 1024]
unified_message -> Varchar,
#[max_length = 255]
locale -> Varchar,
#[max_length = 1024]
translation -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_authentication_methods (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
auth_id -> Varchar,
#[max_length = 64]
owner_id -> Varchar,
#[max_length = 64]
owner_type -> Varchar,
#[max_length = 64]
auth_type -> Varchar,
private_config -> Nullable<Bytea>,
public_config -> Nullable<Jsonb>,
allow_signup -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
email_domain -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_key_store (user_id) {
#[max_length = 64]
user_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_roles (id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
status -> UserStatus,
#[max_length = 64]
created_by -> Varchar,
#[max_length = 64]
last_modified_by -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
entity_id -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Nullable<Varchar>,
version -> UserRoleVersion,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
users (user_id) {
#[max_length = 64]
user_id -> Varchar,
#[max_length = 255]
email -> Varchar,
#[max_length = 255]
name -> Varchar,
#[max_length = 255]
password -> Nullable<Varchar>,
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
totp_status -> TotpStatus,
totp_secret -> Nullable<Bytea>,
totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
lineage_context -> Nullable<Jsonb>,
}
}
diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
authentication,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
business_profile,
callback_mapper,
captures,
cards_info,
configs,
customers,
dashboard_metadata,
dispute,
dynamic_routing_stats,
events,
file_metadata,
fraud_check,
gateway_status_map,
generic_link,
hyperswitch_ai_interaction,
hyperswitch_ai_interaction_default,
incremental_authorization,
invoice,
locker_mock_up,
mandate,
merchant_account,
merchant_connector_account,
merchant_key_store,
organization,
payment_attempt,
payment_intent,
payment_link,
payment_methods,
payout_attempt,
payouts,
process_tracker,
refund,
relay,
reverse_lookup,
roles,
routing_algorithm,
subscription,
themes,
tokenization,
unified_translations,
user_authentication_methods,
user_key_store,
user_roles,
users,
);
| {
"crate": "diesel_models",
"file": "crates/diesel_models/src/schema_v2.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": null,
"num_tables": 50,
"score": null,
"total_crates": null
} |
diesel_file_6082001395469778501 | clm | file | // Repository: hyperswitch
// Crate: diesel_models
// File: crates/diesel_models/src/schema.rs
// Contains: 49 table schemas, 0 diesel enums
// @generated automatically by Diesel CLI.
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
address (address_id) {
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
city -> Nullable<Varchar>,
country -> Nullable<CountryAlpha2>,
line1 -> Nullable<Bytea>,
line2 -> Nullable<Bytea>,
line3 -> Nullable<Bytea>,
state -> Nullable<Bytea>,
zip -> Nullable<Bytea>,
first_name -> Nullable<Bytea>,
last_name -> Nullable<Bytea>,
phone_number -> Nullable<Bytea>,
#[max_length = 8]
country_code -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
email -> Nullable<Bytea>,
origin_zip -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
api_keys (key_id) {
#[max_length = 64]
key_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
#[max_length = 128]
hashed_api_key -> Varchar,
#[max_length = 16]
prefix -> Varchar,
created_at -> Timestamp,
expires_at -> Nullable<Timestamp>,
last_used -> Nullable<Timestamp>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
authentication (authentication_id) {
#[max_length = 64]
authentication_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
connector_authentication_id -> Nullable<Varchar>,
authentication_data -> Nullable<Jsonb>,
#[max_length = 64]
payment_method_id -> Varchar,
#[max_length = 64]
authentication_type -> Nullable<Varchar>,
#[max_length = 64]
authentication_status -> Varchar,
#[max_length = 64]
authentication_lifecycle_status -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
maximum_supported_version -> Nullable<Jsonb>,
#[max_length = 64]
threeds_server_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
cavv -> Nullable<Varchar>,
#[max_length = 64]
authentication_flow_type -> Nullable<Varchar>,
message_version -> Nullable<Jsonb>,
#[max_length = 64]
eci -> Nullable<Varchar>,
#[max_length = 64]
trans_status -> Nullable<Varchar>,
#[max_length = 64]
acquirer_bin -> Nullable<Varchar>,
#[max_length = 64]
acquirer_merchant_id -> Nullable<Varchar>,
three_ds_method_data -> Nullable<Varchar>,
three_ds_method_url -> Nullable<Varchar>,
acs_url -> Nullable<Varchar>,
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 255]
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
#[max_length = 64]
acquirer_country_code -> Nullable<Varchar>,
service_details -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 128]
authentication_client_secret -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
#[max_length = 2048]
return_url -> Nullable<Varchar>,
amount -> Nullable<Int8>,
currency -> Nullable<Currency>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
browser_info -> Nullable<Jsonb>,
email -> Nullable<Bytea>,
#[max_length = 128]
profile_acquirer_id -> Nullable<Varchar>,
challenge_code -> Nullable<Varchar>,
challenge_cancel -> Nullable<Varchar>,
challenge_code_reason -> Nullable<Varchar>,
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_fingerprint (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
encrypted_fingerprint -> Text,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_lookup (merchant_id, fingerprint) {
#[max_length = 64]
merchant_id -> Varchar,
fingerprint -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
business_profile (profile_id) {
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_name -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
return_url -> Nullable<Text>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
routing_algorithm -> Nullable<Json>,
intent_fulfillment_time -> Nullable<Int8>,
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
payout_link_config -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
always_request_extended_authorization -> Nullable<Bool>,
is_click_to_pay_enabled -> Bool,
authentication_product_ids -> Nullable<Jsonb>,
card_testing_guard_config -> Nullable<Jsonb>,
card_testing_secret_key -> Nullable<Bytea>,
is_clear_pan_retries_enabled -> Bool,
force_3ds_challenge -> Nullable<Bool>,
is_debit_routing_enabled -> Bool,
merchant_business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
id -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
is_pre_network_tokenization_enabled -> Nullable<Bool>,
three_ds_decision_rule_algorithm -> Nullable<Jsonb>,
acquirer_config_map -> Nullable<Jsonb>,
#[max_length = 16]
merchant_category_code -> Nullable<Varchar>,
#[max_length = 32]
merchant_country_code -> Nullable<Varchar>,
dispute_polling_interval -> Nullable<Int4>,
is_manual_retry_enabled -> Nullable<Bool>,
always_enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
billing_processor_id -> Nullable<Varchar>,
is_external_vault_enabled -> Nullable<Bool>,
external_vault_connector_details -> Nullable<Jsonb>,
is_l2_l3_enabled -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
callback_mapper (id, type_) {
#[max_length = 128]
id -> Varchar,
#[sql_name = "type"]
#[max_length = 64]
type_ -> Varchar,
data -> Jsonb,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
captures (capture_id) {
#[max_length = 64]
capture_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> CaptureStatus,
amount -> Int8,
currency -> Nullable<Currency>,
#[max_length = 255]
connector -> Varchar,
#[max_length = 255]
error_message -> Nullable<Varchar>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 255]
error_reason -> Nullable<Varchar>,
tax_amount -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
authorized_attempt_id -> Varchar,
#[max_length = 128]
connector_capture_id -> Nullable<Varchar>,
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
#[max_length = 512]
connector_capture_data -> Nullable<Varchar>,
processor_capture_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
cards_info (card_iin) {
#[max_length = 16]
card_iin -> Varchar,
card_issuer -> Nullable<Text>,
card_network -> Nullable<Text>,
card_type -> Nullable<Text>,
card_subtype -> Nullable<Text>,
card_issuing_country -> Nullable<Text>,
#[max_length = 32]
bank_code_id -> Nullable<Varchar>,
#[max_length = 32]
bank_code -> Nullable<Varchar>,
#[max_length = 32]
country_code -> Nullable<Varchar>,
date_created -> Timestamp,
last_updated -> Nullable<Timestamp>,
last_updated_provider -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
configs (key) {
#[max_length = 255]
key -> Varchar,
config -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
customers (customer_id, merchant_id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
name -> Nullable<Bytea>,
email -> Nullable<Bytea>,
phone -> Nullable<Bytea>,
#[max_length = 8]
phone_country_code -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
created_at -> Timestamp,
metadata -> Nullable<Json>,
connector_customer -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
default_payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
tax_registration_id -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dashboard_metadata (id) {
id -> Int4,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
org_id -> Varchar,
data_key -> DashboardMetadata,
data_value -> Json,
#[max_length = 64]
created_by -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
amount -> Varchar,
#[max_length = 255]
currency -> Varchar,
dispute_stage -> DisputeStage,
dispute_status -> DisputeStatus,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
connector_status -> Varchar,
#[max_length = 255]
connector_dispute_id -> Varchar,
#[max_length = 255]
connector_reason -> Nullable<Varchar>,
#[max_length = 255]
connector_reason_code -> Nullable<Varchar>,
challenge_required_by -> Nullable<Timestamp>,
connector_created_at -> Nullable<Timestamp>,
connector_updated_at -> Nullable<Timestamp>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
connector -> Varchar,
evidence -> Jsonb,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
#[max_length = 32]
organization_id -> Varchar,
dispute_currency -> Nullable<Currency>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dynamic_routing_stats (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
amount -> Int8,
#[max_length = 64]
success_based_routing_connector -> Varchar,
#[max_length = 64]
payment_connector -> Varchar,
currency -> Nullable<Currency>,
#[max_length = 64]
payment_method -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
payment_status -> AttemptStatus,
conclusive_classification -> SuccessBasedRoutingConclusiveState,
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 64]
global_success_based_connector -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
event_type -> EventType,
event_class -> EventClass,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
primary_object_type -> EventObjectType,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
business_profile_id -> Nullable<Varchar>,
primary_object_created_at -> Nullable<Timestamp>,
#[max_length = 64]
idempotent_event_id -> Nullable<Varchar>,
#[max_length = 64]
initial_attempt_id -> Nullable<Varchar>,
request -> Nullable<Bytea>,
response -> Nullable<Bytea>,
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
file_metadata (file_id, merchant_id) {
#[max_length = 64]
file_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
file_name -> Nullable<Varchar>,
file_size -> Int4,
#[max_length = 255]
file_type -> Varchar,
#[max_length = 255]
provider_file_id -> Nullable<Varchar>,
#[max_length = 255]
file_upload_provider -> Nullable<Varchar>,
available -> Bool,
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
created_at -> Timestamp,
#[max_length = 255]
frm_name -> Varchar,
#[max_length = 255]
frm_transaction_id -> Nullable<Varchar>,
frm_transaction_type -> FraudCheckType,
frm_status -> FraudCheckStatus,
frm_score -> Nullable<Int4>,
frm_reason -> Nullable<Jsonb>,
#[max_length = 255]
frm_error -> Nullable<Varchar>,
payment_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
payment_capture_method -> Nullable<CaptureMethod>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
gateway_status_map (connector, flow, sub_flow, code, message) {
#[max_length = 64]
connector -> Varchar,
#[max_length = 64]
flow -> Varchar,
#[max_length = 64]
sub_flow -> Varchar,
#[max_length = 255]
code -> Varchar,
#[max_length = 1024]
message -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 64]
router_error -> Nullable<Varchar>,
#[max_length = 64]
decision -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
step_up_possible -> Bool,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
#[max_length = 64]
error_category -> Nullable<Varchar>,
clear_pan_possible -> Bool,
feature_data -> Nullable<Jsonb>,
#[max_length = 64]
feature -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
generic_link (link_id) {
#[max_length = 64]
link_id -> Varchar,
#[max_length = 64]
primary_reference -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
expiry -> Timestamp,
link_data -> Jsonb,
link_status -> Jsonb,
link_type -> GenericLinkType,
url -> Text,
return_url -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction_default (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
incremental_authorization (authorization_id, merchant_id) {
#[max_length = 64]
authorization_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
amount -> Int8,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
#[max_length = 64]
connector_authorization_id -> Nullable<Varchar>,
previously_authorized_amount -> Int8,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
invoice (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
subscription_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_connector_id -> Varchar,
#[max_length = 64]
payment_intent_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
customer_id -> Varchar,
amount -> Int8,
#[max_length = 3]
currency -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 128]
provider_name -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
connector_invoice_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
locker_mock_up (card_id) {
#[max_length = 255]
card_id -> Varchar,
#[max_length = 255]
external_id -> Varchar,
#[max_length = 255]
card_fingerprint -> Varchar,
#[max_length = 255]
card_global_fingerprint -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
card_number -> Varchar,
#[max_length = 255]
card_exp_year -> Varchar,
#[max_length = 255]
card_exp_month -> Varchar,
#[max_length = 255]
name_on_card -> Nullable<Varchar>,
#[max_length = 255]
nickname -> Nullable<Varchar>,
#[max_length = 255]
customer_id -> Nullable<Varchar>,
duplicate -> Nullable<Bool>,
#[max_length = 8]
card_cvc -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
enc_card_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
mandate_status -> MandateStatus,
mandate_type -> MandateType,
customer_accepted_at -> Nullable<Timestamp>,
#[max_length = 64]
customer_ip_address -> Nullable<Varchar>,
#[max_length = 255]
customer_user_agent -> Nullable<Varchar>,
#[max_length = 128]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
previous_attempt_id -> Nullable<Varchar>,
created_at -> Timestamp,
mandate_amount -> Nullable<Int8>,
mandate_currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_mandate_id -> Nullable<Varchar>,
start_date -> Nullable<Timestamp>,
end_date -> Nullable<Timestamp>,
metadata -> Nullable<Jsonb>,
connector_mandate_ids -> Nullable<Jsonb>,
#[max_length = 64]
original_payment_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
#[max_length = 2048]
customer_user_agent_extended -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_account (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 255]
return_url -> Nullable<Varchar>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
merchant_name -> Nullable<Bytea>,
merchant_details -> Nullable<Bytea>,
webhook_details -> Nullable<Json>,
sub_merchants_enabled -> Nullable<Bool>,
#[max_length = 64]
parent_merchant_id -> Nullable<Varchar>,
#[max_length = 128]
publishable_key -> Nullable<Varchar>,
storage_scheme -> MerchantStorageScheme,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
routing_algorithm -> Nullable<Json>,
primary_business_details -> Json,
intent_fulfillment_time -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
is_recon_enabled -> Bool,
#[max_length = 64]
default_profile -> Nullable<Varchar>,
recon_status -> ReconStatus,
payment_link_config -> Nullable<Jsonb>,
pm_collect_link_config -> Nullable<Jsonb>,
version -> ApiVersion,
is_platform_account -> Bool,
#[max_length = 64]
id -> Nullable<Varchar>,
#[max_length = 64]
product_type -> Nullable<Varchar>,
#[max_length = 64]
merchant_account_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_connector_account (merchant_connector_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
connector_name -> Varchar,
connector_account_details -> Bytea,
test_mode -> Nullable<Bool>,
disabled -> Nullable<Bool>,
#[max_length = 128]
merchant_connector_id -> Varchar,
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 255]
business_label -> Nullable<Varchar>,
#[max_length = 64]
business_sub_label -> Nullable<Varchar>,
frm_configs -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
connector_webhook_details -> Nullable<Jsonb>,
frm_config -> Nullable<Array<Nullable<Jsonb>>>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
version -> ApiVersion,
#[max_length = 64]
id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_key_store (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
organization (org_id) {
#[max_length = 32]
org_id -> Varchar,
org_name -> Nullable<Text>,
organization_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
id -> Nullable<Varchar>,
organization_name -> Nullable<Text>,
version -> ApiVersion,
#[max_length = 64]
organization_type -> Nullable<Varchar>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_attempt (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
status -> AttemptStatus,
amount -> Int8,
currency -> Nullable<Currency>,
save_to_locker -> Nullable<Bool>,
#[max_length = 64]
connector -> Nullable<Varchar>,
error_message -> Nullable<Text>,
offer_amount -> Nullable<Int8>,
surcharge_amount -> Nullable<Int8>,
tax_amount -> Nullable<Int8>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
payment_method -> Nullable<Varchar>,
#[max_length = 128]
connector_transaction_id -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
capture_on -> Nullable<Timestamp>,
confirm -> Bool,
authentication_type -> Nullable<AuthenticationType>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
#[max_length = 255]
cancellation_reason -> Nullable<Varchar>,
amount_to_capture -> Nullable<Int8>,
#[max_length = 64]
mandate_id -> Nullable<Varchar>,
browser_info -> Nullable<Jsonb>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 128]
payment_token -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
#[max_length = 50]
payment_experience -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
payment_method_data -> Nullable<Jsonb>,
#[max_length = 64]
business_sub_label -> Nullable<Varchar>,
straight_through_algorithm -> Nullable<Jsonb>,
preprocessing_step_id -> Nullable<Varchar>,
mandate_details -> Nullable<Jsonb>,
error_reason -> Nullable<Text>,
multiple_capture_count -> Nullable<Int2>,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
amount_capturable -> Int8,
#[max_length = 32]
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
authentication_data -> Nullable<Json>,
encoded_data -> Nullable<Text>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
net_amount -> Nullable<Int8>,
external_three_ds_authentication_attempted -> Nullable<Bool>,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
authentication_id -> Nullable<Varchar>,
mandate_data -> Nullable<Jsonb>,
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_billing_address_id -> Nullable<Varchar>,
#[max_length = 64]
charge_id -> Nullable<Varchar>,
#[max_length = 64]
client_source -> Nullable<Varchar>,
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 32]
card_network -> Nullable<Varchar>,
shipping_cost -> Nullable<Int8>,
order_tax_amount -> Nullable<Int8>,
#[max_length = 512]
connector_transaction_data -> Nullable<Varchar>,
connector_mandate_detail -> Nullable<Jsonb>,
request_extended_authorization -> Nullable<Bool>,
extended_authorization_applied -> Nullable<Bool>,
capture_before -> Nullable<Timestamp>,
processor_transaction_data -> Nullable<Text>,
card_discovery -> Nullable<CardDiscovery>,
charges -> Nullable<Jsonb>,
#[max_length = 64]
issuer_error_code -> Nullable<Varchar>,
issuer_error_message -> Nullable<Text>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
setup_future_usage_applied -> Nullable<FutureUsage>,
routing_approach -> Nullable<RoutingApproach>,
#[max_length = 255]
connector_request_reference_id -> Nullable<Varchar>,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
is_overcapture_enabled -> Nullable<Bool>,
network_details -> Nullable<Jsonb>,
is_stored_credential -> Nullable<Bool>,
authorized_amount -> Nullable<Int8>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_intent (payment_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> IntentStatus,
amount -> Int8,
currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 255]
return_url -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
#[max_length = 64]
connector_id -> Nullable<Varchar>,
#[max_length = 64]
shipping_address_id -> Nullable<Varchar>,
#[max_length = 64]
billing_address_id -> Nullable<Varchar>,
#[max_length = 255]
statement_descriptor_name -> Nullable<Varchar>,
#[max_length = 255]
statement_descriptor_suffix -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
setup_future_usage -> Nullable<FutureUsage>,
off_session -> Nullable<Bool>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 64]
active_attempt_id -> Varchar,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
business_label -> Nullable<Varchar>,
order_details -> Nullable<Array<Nullable<Jsonb>>>,
allowed_payment_method_types -> Nullable<Json>,
connector_metadata -> Nullable<Json>,
feature_metadata -> Nullable<Json>,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_decision -> Nullable<Varchar>,
#[max_length = 255]
payment_link_id -> Nullable<Varchar>,
payment_confirm_source -> Nullable<PaymentSource>,
#[max_length = 32]
updated_by -> Varchar,
surcharge_applicable -> Nullable<Bool>,
request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>,
incremental_authorization_allowed -> Nullable<Bool>,
authorization_count -> Nullable<Int4>,
session_expiry -> Nullable<Timestamp>,
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
request_external_three_ds_authentication -> Nullable<Bool>,
charges -> Nullable<Jsonb>,
frm_metadata -> Nullable<Jsonb>,
customer_details -> Nullable<Bytea>,
billing_details -> Nullable<Bytea>,
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
is_payment_processor_token_flow -> Nullable<Bool>,
shipping_cost -> Nullable<Int8>,
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
skip_external_tax_calculation -> Nullable<Bool>,
request_extended_authorization -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
split_payments -> Nullable<Jsonb>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
force_3ds_challenge_trigger -> Nullable<Bool>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
#[max_length = 2048]
extended_return_url -> Nullable<Varchar>,
is_payment_id_from_merchant -> Nullable<Bool>,
#[max_length = 64]
payment_channel -> Nullable<Varchar>,
tax_status -> Nullable<Varchar>,
discount_amount -> Nullable<Int8>,
shipping_amount_tax -> Nullable<Int8>,
duty_amount -> Nullable<Int8>,
order_date -> Nullable<Timestamp>,
enable_partial_authorization -> Nullable<Bool>,
enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
mit_category -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_link (payment_link_id) {
#[max_length = 255]
payment_link_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 255]
link_to_pay -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
amount -> Int8,
currency -> Nullable<Currency>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
fulfilment_time -> Nullable<Timestamp>,
#[max_length = 64]
custom_merchant_name -> Nullable<Varchar>,
payment_link_config -> Nullable<Jsonb>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 255]
secure_link -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_methods (payment_method_id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
accepted_currency -> Nullable<Array<Nullable<Currency>>>,
#[max_length = 32]
scheme -> Nullable<Varchar>,
#[max_length = 128]
token -> Nullable<Varchar>,
#[max_length = 255]
cardholder_name -> Nullable<Varchar>,
#[max_length = 64]
issuer_name -> Nullable<Varchar>,
#[max_length = 64]
issuer_country -> Nullable<Varchar>,
payer_country -> Nullable<Array<Nullable<Text>>>,
is_stored -> Nullable<Bool>,
#[max_length = 32]
swift_code -> Nullable<Varchar>,
#[max_length = 128]
direct_debit_token -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified -> Timestamp,
payment_method -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 128]
payment_method_issuer -> Nullable<Varchar>,
payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
last_used_at -> Timestamp,
connector_mandate_details -> Nullable<Jsonb>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
payment_method_billing_address -> Nullable<Bytea>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
#[max_length = 128]
network_token_requestor_reference_id -> Nullable<Varchar>,
#[max_length = 64]
network_token_locker_id -> Nullable<Varchar>,
network_token_payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
external_vault_source -> Nullable<Varchar>,
#[max_length = 64]
vault_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payout_attempt (merchant_id, payout_attempt_id) {
#[max_length = 64]
payout_attempt_id -> Varchar,
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
connector -> Nullable<Varchar>,
#[max_length = 128]
connector_payout_id -> Nullable<Varchar>,
#[max_length = 64]
payout_token -> Nullable<Varchar>,
status -> PayoutStatus,
is_eligible -> Nullable<Bool>,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
business_label -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
routing_info -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
additional_payout_method_data -> Nullable<Jsonb>,
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
payout_connector_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payouts (merchant_id, payout_id) {
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
address_id -> Nullable<Varchar>,
payout_type -> Nullable<PayoutType>,
#[max_length = 64]
payout_method_id -> Nullable<Varchar>,
amount -> Int8,
destination_currency -> Currency,
source_currency -> Currency,
#[max_length = 255]
description -> Nullable<Varchar>,
recurring -> Bool,
auto_fulfill -> Bool,
#[max_length = 255]
return_url -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Varchar,
status -> PayoutStatus,
confirm -> Nullable<Bool>,
#[max_length = 255]
payout_link_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 32]
priority -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
process_tracker (id) {
#[max_length = 127]
id -> Varchar,
#[max_length = 64]
name -> Nullable<Varchar>,
tag -> Array<Nullable<Text>>,
#[max_length = 64]
runner -> Nullable<Varchar>,
retry_count -> Int4,
schedule_time -> Nullable<Timestamp>,
#[max_length = 255]
rule -> Varchar,
tracking_data -> Json,
#[max_length = 255]
business_status -> Varchar,
status -> ProcessTrackerStatus,
event -> Array<Nullable<Text>>,
created_at -> Timestamp,
updated_at -> Timestamp,
version -> ApiVersion,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
refund (merchant_id, refund_id) {
#[max_length = 64]
internal_reference_id -> Varchar,
#[max_length = 64]
refund_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 128]
connector_transaction_id -> Varchar,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_refund_id -> Nullable<Varchar>,
#[max_length = 64]
external_reference_id -> Nullable<Varchar>,
refund_type -> RefundType,
total_amount -> Int8,
currency -> Currency,
refund_amount -> Int8,
refund_status -> RefundStatus,
sent_to_gateway -> Bool,
refund_error_message -> Nullable<Text>,
metadata -> Nullable<Json>,
#[max_length = 128]
refund_arn -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
refund_reason -> Nullable<Varchar>,
refund_error_code -> Nullable<Text>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
charges -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 512]
connector_refund_data -> Nullable<Varchar>,
#[max_length = 512]
connector_transaction_data -> Nullable<Varchar>,
split_refunds -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
processor_refund_data -> Nullable<Text>,
processor_transaction_data -> Nullable<Text>,
#[max_length = 64]
issuer_error_code -> Nullable<Varchar>,
issuer_error_message -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
relay (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
connector_resource_id -> Varchar,
#[max_length = 64]
connector_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
relay_type -> RelayType,
request_data -> Nullable<Jsonb>,
status -> RelayStatus,
#[max_length = 128]
connector_reference_id -> Nullable<Varchar>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
created_at -> Timestamp,
modified_at -> Timestamp,
response_data -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
reverse_lookup (lookup_id) {
#[max_length = 128]
lookup_id -> Varchar,
#[max_length = 128]
sk_id -> Varchar,
#[max_length = 128]
pk_id -> Varchar,
#[max_length = 128]
source -> Varchar,
#[max_length = 32]
updated_by -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
roles (role_id) {
#[max_length = 64]
role_name -> Varchar,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Varchar,
groups -> Array<Nullable<Text>>,
scope -> RoleScope,
created_at -> Timestamp,
#[max_length = 64]
created_by -> Varchar,
last_modified_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
routing_algorithm (algorithm_id) {
#[max_length = 64]
algorithm_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
kind -> RoutingAlgorithmKind,
algorithm_data -> Jsonb,
created_at -> Timestamp,
modified_at -> Timestamp,
algorithm_for -> TransactionType,
#[max_length = 64]
decision_engine_routing_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
subscription (id) {
#[max_length = 128]
id -> Varchar,
#[max_length = 128]
status -> Varchar,
#[max_length = 128]
billing_processor -> Nullable<Varchar>,
#[max_length = 128]
payment_method_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 128]
connector_subscription_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_reference_id -> Nullable<Varchar>,
#[max_length = 128]
plan_id -> Nullable<Varchar>,
#[max_length = 128]
item_price_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
themes (theme_id) {
#[max_length = 64]
theme_id -> Varchar,
#[max_length = 64]
tenant_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
theme_name -> Varchar,
#[max_length = 64]
email_primary_color -> Varchar,
#[max_length = 64]
email_foreground_color -> Varchar,
#[max_length = 64]
email_background_color -> Varchar,
#[max_length = 64]
email_entity_name -> Varchar,
email_entity_logo_url -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
unified_translations (unified_code, unified_message, locale) {
#[max_length = 255]
unified_code -> Varchar,
#[max_length = 1024]
unified_message -> Varchar,
#[max_length = 255]
locale -> Varchar,
#[max_length = 1024]
translation -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_authentication_methods (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
auth_id -> Varchar,
#[max_length = 64]
owner_id -> Varchar,
#[max_length = 64]
owner_type -> Varchar,
#[max_length = 64]
auth_type -> Varchar,
private_config -> Nullable<Bytea>,
public_config -> Nullable<Jsonb>,
allow_signup -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
email_domain -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_key_store (user_id) {
#[max_length = 64]
user_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_roles (id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
status -> UserStatus,
#[max_length = 64]
created_by -> Varchar,
#[max_length = 64]
last_modified_by -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
entity_id -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Nullable<Varchar>,
version -> UserRoleVersion,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
users (user_id) {
#[max_length = 64]
user_id -> Varchar,
#[max_length = 255]
email -> Varchar,
#[max_length = 255]
name -> Varchar,
#[max_length = 255]
password -> Nullable<Varchar>,
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
totp_status -> TotpStatus,
totp_secret -> Nullable<Bytea>,
totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
lineage_context -> Nullable<Jsonb>,
}
}
diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
authentication,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
business_profile,
callback_mapper,
captures,
cards_info,
configs,
customers,
dashboard_metadata,
dispute,
dynamic_routing_stats,
events,
file_metadata,
fraud_check,
gateway_status_map,
generic_link,
hyperswitch_ai_interaction,
hyperswitch_ai_interaction_default,
incremental_authorization,
invoice,
locker_mock_up,
mandate,
merchant_account,
merchant_connector_account,
merchant_key_store,
organization,
payment_attempt,
payment_intent,
payment_link,
payment_methods,
payout_attempt,
payouts,
process_tracker,
refund,
relay,
reverse_lookup,
roles,
routing_algorithm,
subscription,
themes,
unified_translations,
user_authentication_methods,
user_key_store,
user_roles,
users,
);
| {
"crate": "diesel_models",
"file": "crates/diesel_models/src/schema.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": null,
"num_tables": 49,
"score": null,
"total_crates": null
} |
diesel_file_5933697906134899615 | clm | file | // Repository: hyperswitch
// Crate: diesel_models
// File: crates/diesel_models/src/enums.rs
// Contains: 0 table schemas, 10 diesel enums
#[doc(hidden)]
pub mod diesel_exports {
pub use super::{
DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus,
DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind,
DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus,
DbCardDiscovery as CardDiscovery, DbConnectorStatus as ConnectorStatus,
DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus,
DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus,
DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType,
DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType,
DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType,
DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus,
DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme,
DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin,
DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource,
DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType,
DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus,
DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRelayStatus as RelayStatus,
DbRelayType as RelayType,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRevenueRecoveryAlgorithmType as RevenueRecoveryAlgorithmType, DbRoleScope as RoleScope,
DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbRoutingApproach as RoutingApproach,
DbScaExemptionType as ScaExemptionType,
DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState,
DbTokenizationFlag as TokenizationFlag, DbTotpStatus as TotpStatus,
DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion,
DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub use common_enums::*;
use common_utils::pii;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub use common_utils::tokenization;
use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb};
use router_derive::diesel_enum;
use time::PrimitiveDateTime;
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingAlgorithmKind {
Single,
Priority,
VolumeSplit,
Advanced,
Dynamic,
ThreeDsDecisionRule,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EventObjectType {
PaymentDetails,
RefundDetails,
DisputeDetails,
MandateDetails,
PayoutDetails,
}
// Refund
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundType {
InstantRefund,
RegularRefund,
RetryRefund,
}
// Mandate
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Default,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateType {
SingleUse,
#[default]
MultiUse,
}
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
}
common_utils::impl_to_sql_from_sql_json!(MandateDetails);
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
common_utils::impl_to_sql_from_sql_json!(MandateDataType);
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: common_utils::types::MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FraudCheckType {
PreFrm,
PostFrm,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
pub enum FraudCheckLastStep {
#[default]
Processing,
CheckoutOrSale,
TransactionOrRecordRefund,
Fulfillment,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UserStatus {
Active,
#[default]
InvitationSent,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DashboardMetadata {
ProductionAgreement,
SetupProcessor,
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected,
SecondProcessorConnected,
ConfiguredRouting,
TestPayment,
IntegrationMethod,
ConfigurationType,
IntegrationCompleted,
StripeConnected,
PaypalConnected,
SpRoutingConfigured,
Feedback,
ProdIntent,
SpTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
OnboardingSurvey,
ReconStatus,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TotpStatus {
Set,
InProgress,
#[default]
NotSet,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
strum::Display,
)]
#[diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UserRoleVersion {
#[default]
V1,
V2,
}
| {
"crate": "diesel_models",
"file": "crates/diesel_models/src/enums.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 10,
"num_structs": null,
"num_tables": 0,
"score": null,
"total_crates": null
} |
fn_clm_storage_impl_get_entity_id_vault_id_by_token_id_-3120060625278092666 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/tokenization
// Implementation of MockDb for TokenizationInterface
async fn get_entity_id_vault_id_by_token_id(
&self,
_token: &common_utils::id_type::GlobalTokenId,
_merchant_key_store: &MerchantKeyStore,
_key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
{
Err(errors::StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_storage_impl_insert_tokenization_-3120060625278092666 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/tokenization
// Implementation of MockDb for TokenizationInterface
async fn insert_tokenization(
&self,
_tokenization: hyperswitch_domain_models::tokenization::Tokenization,
_merchant_key_store: &MerchantKeyStore,
_key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
{
Err(errors::StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_update_tokenization_record_-3120060625278092666 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/tokenization
// Implementation of MockDb for TokenizationInterface
async fn update_tokenization_record(
&self,
tokenization_record: hyperswitch_domain_models::tokenization::Tokenization,
tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
merchant_key_store: &MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
{
Err(errors::StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_new_4897890901229739837 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/mock_db
// Inherent implementation for MockDb
pub async fn new(redis: &RedisSettings) -> error_stack::Result<Self, StorageError> {
Ok(Self {
addresses: Default::default(),
configs: Default::default(),
merchant_accounts: Default::default(),
merchant_connector_accounts: Default::default(),
payment_attempts: Default::default(),
payment_intents: Default::default(),
payment_methods: Default::default(),
customers: Default::default(),
refunds: Default::default(),
processes: Default::default(),
redis: Arc::new(
RedisStore::new(redis)
.await
.change_context(StorageError::InitializationError)?,
),
api_keys: Default::default(),
ephemeral_keys: Default::default(),
cards_info: Default::default(),
events: Default::default(),
disputes: Default::default(),
lockers: Default::default(),
mandates: Default::default(),
captures: Default::default(),
merchant_key_store: Default::default(),
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
tokenizations: Default::default(),
business_profiles: Default::default(),
reverse_lookups: Default::default(),
payment_link: Default::default(),
organizations: Default::default(),
users: Default::default(),
user_roles: Default::default(),
authorizations: Default::default(),
dashboard_metadata: Default::default(),
#[cfg(feature = "payouts")]
payout_attempt: Default::default(),
#[cfg(feature = "payouts")]
payouts: Default::default(),
authentications: Default::default(),
roles: Default::default(),
user_key_store: Default::default(),
user_authentication_methods: Default::default(),
themes: Default::default(),
hyperswitch_ai_interactions: Default::default(),
})
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14541,
"total_crates": null
} |
fn_clm_storage_impl_get_resources_4897890901229739837 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/mock_db
// Inherent implementation for MockDb
pub async fn get_resources<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
resources: MutexGuard<'_, Vec<D>>,
filter_fn: impl Fn(&&D) -> bool,
error_message: String,
) -> CustomResult<Vec<R>, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
let resources: Vec<_> = resources.iter().filter(filter_fn).cloned().collect();
if resources.is_empty() {
Err(StorageError::ValueNotFound(error_message).into())
} else {
let pm_futures = resources
.into_iter()
.map(|pm| async {
pm.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.collect::<Vec<_>>();
let domain_resources = futures::future::try_join_all(pm_futures).await?;
Ok(domain_resources)
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 57,
"total_crates": null
} |
fn_clm_storage_impl_find_resource_4897890901229739837 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/mock_db
// Inherent implementation for MockDb
/// Returns an option of the resource if it exists
pub async fn find_resource<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
resources: MutexGuard<'_, Vec<D>>,
filter_fn: impl Fn(&&D) -> bool,
) -> CustomResult<Option<R>, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
let resource = resources.iter().find(filter_fn).cloned();
match resource {
Some(res) => Ok(Some(
res.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)),
None => Ok(None),
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_storage_impl_update_resource_4897890901229739837 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/mock_db
// Inherent implementation for MockDb
pub async fn update_resource<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
mut resources: MutexGuard<'_, Vec<D>>,
resource_updated: D,
filter_fn: impl Fn(&&mut D) -> bool,
error_message: String,
) -> CustomResult<R, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
if let Some(pm) = resources.iter_mut().find(filter_fn) {
*pm = resource_updated.clone();
let result = resource_updated
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(result)
} else {
Err(StorageError::ValueNotFound(error_message).into())
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_storage_impl_get_resource_4897890901229739837 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/mock_db
// Inherent implementation for MockDb
/// Throws errors when the requested resource is not found
pub async fn get_resource<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
resources: MutexGuard<'_, Vec<D>>,
filter_fn: impl Fn(&&D) -> bool,
error_message: String,
) -> CustomResult<R, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
match self
.find_resource(state, key_store, resources, filter_fn)
.await?
{
Some(res) => Ok(res),
None => Err(StorageError::ValueNotFound(error_message).into()),
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_storage_impl_to_storage_model_3052669159042791025 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/callback_mapper
// Implementation of CallbackMapper for DataModelExt
fn to_storage_model(self) -> Self::StorageModel {
DieselCallbackMapper {
id: self.id,
type_: self.callback_mapper_id_type,
data: self.data,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_storage_impl_from_storage_model_3052669159042791025 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/callback_mapper
// Implementation of CallbackMapper for DataModelExt
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
id: storage_model.id,
callback_mapper_id_type: storage_model.type_,
data: storage_model.data,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 17,
"total_crates": null
} |
fn_clm_storage_impl_insert_reverse_lookup_4819465489939682817 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lookup
// Implementation of KVRouterStore<T> for ReverseLookupInterface
async fn insert_reverse_lookup(
&self,
new: DieselReverseLookupNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_reverse_lookup(new, storage_scheme)
.await
}
storage_enums::MerchantStorageScheme::RedisKv => {
let created_rev_lookup = DieselReverseLookup {
lookup_id: new.lookup_id.clone(),
sk_id: new.sk_id.clone(),
pk_id: new.pk_id.clone(),
source: new.source.clone(),
updated_by: storage_scheme.to_string(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
},
};
match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>(
self,
KvOperation::SetNx(&created_rev_lookup, redis_entry),
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id),
},
))
.await
.map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))?
.try_into_setnx()
{
Ok(SetnxReply::KeySet) => Ok(created_rev_lookup),
Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "reverse_lookup",
key: Some(created_rev_lookup.lookup_id.clone()),
}
.into()),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 66,
"total_crates": null
} |
fn_clm_storage_impl_get_lookup_by_lookup_id_4819465489939682817 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lookup
// Implementation of KVRouterStore<T> for ReverseLookupInterface
async fn get_lookup_by_lookup_id(
&self,
id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let database_call = || async {
self.router_store
.get_lookup_by_lookup_id(id, storage_scheme)
.await
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await,
storage_enums::MerchantStorageScheme::RedisKv => {
let redis_fut = async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselReverseLookup>::Get,
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{id}"),
},
))
.await?
.try_into_get()
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
database_call,
))
.await
}
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 30,
"total_crates": null
} |
fn_clm_storage_impl_find_merchant_account_by_merchant_id_-1943693745474189190 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_account
// Implementation of MockDb for MerchantAccountInterface
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let accounts = self.merchant_accounts.lock().await;
accounts
.iter()
.find(|account| account.get_id() == merchant_id)
.cloned()
.ok_or(StorageError::ValueNotFound(format!(
"Merchant ID: {merchant_id:?} not found",
)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 164,
"total_crates": null
} |
fn_clm_storage_impl_update_merchant_-1943693745474189190 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_account
// Implementation of MockDb for MerchantAccountInterface
async fn update_merchant(
&self,
state: &KeyManagerState,
merchant_account: domain::MerchantAccount,
merchant_account_update: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let merchant_id = merchant_account.get_id().to_owned();
let mut accounts = self.merchant_accounts.lock().await;
accounts
.iter_mut()
.find(|account| account.get_id() == merchant_account.get_id())
.async_map(|account| async {
let update = MerchantAccountUpdateInternal::from(merchant_account_update)
.apply_changeset(
Conversion::convert(merchant_account)
.await
.change_context(StorageError::EncryptionError)?,
);
*account = update.clone();
update
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",))
.into(),
)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 76,
"total_crates": null
} |
fn_clm_storage_impl_list_multiple_merchant_accounts_-1943693745474189190 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_account
// Implementation of MockDb for MerchantAccountInterface
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
let accounts = self.merchant_accounts.lock().await;
let futures = accounts
.iter()
.filter(|account| merchant_ids.contains(account.get_id()))
.map(|account| async {
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
account.get_id(),
&self.get_master_key().to_vec().into(),
)
.await;
match key_store {
Ok(key) => account
.clone()
.convert(state, key.key.get_inner(), key.merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError),
Err(err) => Err(err),
}
});
futures::future::join_all(futures)
.await
.into_iter()
.collect()
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 60,
"total_crates": null
} |
fn_clm_storage_impl_list_merchant_accounts_by_organization_id_-1943693745474189190 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_account
// Implementation of MockDb for MerchantAccountInterface
async fn list_merchant_accounts_by_organization_id(
&self,
state: &KeyManagerState,
organization_id: &common_utils::id_type::OrganizationId,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
let accounts = self.merchant_accounts.lock().await;
let futures = accounts
.iter()
.filter(|account| account.organization_id == *organization_id)
.map(|account| async {
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
account.get_id(),
&self.get_master_key().to_vec().into(),
)
.await;
match key_store {
Ok(key) => account
.clone()
.convert(state, key.key.get_inner(), key.merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError),
Err(err) => Err(err),
}
});
futures::future::join_all(futures)
.await
.into_iter()
.collect()
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_storage_impl_update_specific_fields_in_merchant_-1943693745474189190 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_account
// Implementation of MockDb for MerchantAccountInterface
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_account_update: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let mut accounts = self.merchant_accounts.lock().await;
accounts
.iter_mut()
.find(|account| account.get_id() == merchant_id)
.async_map(|account| async {
let update = MerchantAccountUpdateInternal::from(merchant_account_update)
.apply_changeset(account.clone());
*account = update.clone();
update
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",))
.into(),
)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_storage_impl_get_card_info_-870014499016733926 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/cards_info
// Implementation of MockDb for CardsInfoInterface
async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> {
Ok(self
.cards_info
.lock()
.await
.iter()
.find(|ci| ci.card_iin == card_iin)
.cloned())
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 49,
"total_crates": null
} |
fn_clm_storage_impl_add_card_info_-870014499016733926 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/cards_info
// Implementation of MockDb for CardsInfoInterface
async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_storage_impl_update_card_info_-870014499016733926 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/cards_info
// Implementation of MockDb for CardsInfoInterface
async fn update_card_info(
&self,
_card_iin: String,
_data: UpdateCardInfo,
) -> CustomResult<CardInfo, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_storage_impl_find_payment_method_6646467183933345871 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/payment_method
// Implementation of MockDb for PaymentMethodInterface
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.get_id() == payment_method_id,
"cannot find payment method".to_string(),
)
.await
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 110,
"total_crates": null
} |
fn_clm_storage_impl_update_payment_method_6646467183933345871 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/payment_method
// Implementation of MockDb for PaymentMethodInterface
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update)
.apply_changeset(
Conversion::convert(payment_method.clone())
.await
.change_context(errors::StorageError::EncryptionError)?,
);
self.update_resource::<PaymentMethod, _>(
state,
key_store,
self.payment_methods.lock().await,
payment_method_updated,
|pm| pm.get_id() == payment_method.get_id(),
"cannot update payment method".to_string(),
)
.await
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 104,
"total_crates": null
} |
fn_clm_storage_impl_delete_payment_method_by_merchant_id_payment_method_id_6646467183933345871 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/payment_method
// Implementation of MockDb for PaymentMethodInterface
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
match payment_methods
.iter()
.position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id)
{
Some(index) => {
let deleted_payment_method = payment_methods.remove(index);
Ok(deleted_payment_method
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?)
}
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method to delete".to_string(),
)
.into()),
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 46,
"total_crates": null
} |
fn_clm_storage_impl_insert_payment_method_6646467183933345871 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/payment_method
// Implementation of MockDb for PaymentMethodInterface
async fn insert_payment_method(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
let pm = Conversion::convert(payment_method.clone())
.await
.change_context(errors::StorageError::DecryptionError)?;
payment_methods.push(pm);
Ok(payment_method)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_storage_impl_delete_payment_method_6646467183933345871 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/payment_method
// Implementation of MockDb for PaymentMethodInterface
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_update = PaymentMethodUpdate::StatusUpdate {
status: Some(common_enums::PaymentMethodStatus::Inactive),
};
let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update)
.apply_changeset(
Conversion::convert(payment_method.clone())
.await
.change_context(errors::StorageError::EncryptionError)?,
);
self.update_resource::<PaymentMethod, _>(
state,
key_store,
self.payment_methods.lock().await,
payment_method_updated,
|pm| pm.get_id() == payment_method.get_id(),
"cannot find payment method".to_string(),
)
.await
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 32,
"total_crates": null
} |
fn_clm_storage_impl_find_by_merchant_connector_account_merchant_id_merchant_connector_id_-6940246591373181949 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_connector_account
// Implementation of MockDb for MerchantConnectorAccountInterface
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
match self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| {
account.merchant_id == *merchant_id
&& account.merchant_connector_id == *merchant_connector_id
})
.cloned()
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
{
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into())
}
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 127,
"total_crates": null
} |
fn_clm_storage_impl_find_merchant_connector_account_by_id_-6940246591373181949 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_connector_account
// Implementation of MockDb for MerchantConnectorAccountInterface
async fn find_merchant_connector_account_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
match self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| account.get_id() == *id)
.cloned()
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
{
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into())
}
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 99,
"total_crates": null
} |
fn_clm_storage_impl_find_merchant_connector_account_by_merchant_id_and_disabled_list_-6940246591373181949 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_connector_account
// Implementation of MockDb for MerchantConnectorAccountInterface
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccounts, StorageError> {
let accounts = self
.merchant_connector_accounts
.lock()
.await
.iter()
.filter(|account: &&storage::MerchantConnectorAccount| {
if get_disabled {
account.merchant_id == *merchant_id
} else {
account.merchant_id == *merchant_id && account.disabled == Some(false)
}
})
.cloned()
.collect::<Vec<storage::MerchantConnectorAccount>>();
let mut output = Vec::with_capacity(accounts.len());
for account in accounts.into_iter() {
output.push(
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)
}
Ok(domain::MerchantConnectorAccounts::new(output))
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 75,
"total_crates": null
} |
fn_clm_storage_impl_find_merchant_connector_account_by_profile_id_connector_name_-6940246591373181949 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_connector_account
// Implementation of MockDb for MerchantConnectorAccountInterface
async fn find_merchant_connector_account_by_profile_id_connector_name(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let maybe_mca = self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| {
account.profile_id.eq(&Some(profile_id.to_owned()))
&& account.connector_name == connector_name
})
.cloned();
match maybe_mca {
Some(mca) => mca
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError),
None => Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into()),
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 62,
"total_crates": null
} |
fn_clm_storage_impl_update_merchant_connector_account_-6940246591373181949 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_connector_account
// Implementation of MockDb for MerchantConnectorAccountInterface
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let mca_update_res = self
.merchant_connector_accounts
.lock()
.await
.iter_mut()
.find(|account| account.get_id() == this.get_id())
.map(|a| {
let updated =
merchant_connector_account.create_merchant_connector_account(a.clone());
*a = updated.clone();
updated
})
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(StorageError::DecryptionError)
})
.await;
match mca_update_res {
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account to update".to_string(),
)
.into())
}
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 53,
"total_crates": null
} |
fn_clm_storage_impl_default_696962529222005614 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/config
// Implementation of Database for Default
fn default() -> Self {
Self {
username: String::new(),
password: Secret::<String>::default(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
queue_strategy: QueueStrategy::default(),
min_idle: None,
max_lifetime: None,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 7713,
"total_crates": null
} |
fn_clm_storage_impl_from_696962529222005614 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/config
// Implementation of bb8::QueueStrategy for From<QueueStrategy>
fn from(value: QueueStrategy) -> Self {
match value {
QueueStrategy::Fifo => Self::Fifo,
QueueStrategy::Lifo => Self::Lifo,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2600,
"total_crates": null
} |
fn_clm_storage_impl_get_master_key_696962529222005614 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/config
// Implementation of MockDb for MasterKeyInterface
fn get_master_key(&self) -> &[u8] {
self.master_key()
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 235,
"total_crates": null
} |
fn_clm_storage_impl_get_password_696962529222005614 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/config
// Implementation of Database for DbConnectionParams
fn get_password(&self) -> Secret<String> {
self.password.clone()
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 13,
"total_crates": null
} |
fn_clm_storage_impl_get_username_696962529222005614 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/config
// Implementation of Database for DbConnectionParams
fn get_username(&self) -> &str {
&self.username
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 8,
"total_crates": null
} |
fn_clm_storage_impl_find_config_by_key_-7356834792137130700 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/configs
// Implementation of MockDb for ConfigInterface
async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> {
let configs = self.configs.lock().await;
let config = configs.iter().find(|c| c.key == key).cloned();
config.ok_or_else(|| StorageError::ValueNotFound("cannot find config".to_string()).into())
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 108,
"total_crates": null
} |
fn_clm_storage_impl_find_config_by_key_unwrap_or_-7356834792137130700 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/configs
// Implementation of MockDb for ConfigInterface
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
_default_config: Option<String>,
) -> CustomResult<storage::Config, Self::Error> {
self.find_config_by_key(key).await
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 70,
"total_crates": null
} |
fn_clm_storage_impl_update_config_by_key_-7356834792137130700 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/configs
// Implementation of MockDb for ConfigInterface
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, Self::Error> {
let result = self
.configs
.lock()
.await
.iter_mut()
.find(|c| c.key == key)
.ok_or_else(|| {
StorageError::ValueNotFound("cannot find config to update".to_string()).into()
})
.map(|c| {
let config_updated =
ConfigUpdateInternal::from(config_update).create_config(c.clone());
*c = config_updated.clone();
config_updated
});
result
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_storage_impl_insert_config_-7356834792137130700 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/configs
// Implementation of MockDb for ConfigInterface
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, Self::Error> {
let mut configs = self.configs.lock().await;
let config_new = storage::Config {
key: config.key,
config: config.config,
};
configs.push(config_new.clone());
Ok(config_new)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_storage_impl_delete_config_by_key_-7356834792137130700 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/configs
// Implementation of MockDb for ConfigInterface
async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> {
let mut configs = self.configs.lock().await;
let result = configs
.iter()
.position(|c| c.key == key)
.map(|index| configs.remove(index))
.ok_or_else(|| {
StorageError::ValueNotFound("cannot find config to delete".to_string()).into()
});
result
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 38,
"total_crates": null
} |
fn_clm_storage_impl_new_5187721350787147080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lib
// Implementation of RouterStore<T> for DatabaseStore
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> error_stack::Result<Self, StorageError> {
let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) =
config;
if test_transaction {
Self::test_store(db_conf, tenant_config, &cache_conf, encryption_key)
.await
.attach_printable("failed to create test router store")
} else {
Self::from_config(
db_conf,
tenant_config,
encryption_key,
Self::cache_store(&cache_conf, cache_error_signal).await?,
inmemory_cache_stream,
)
.await
.attach_printable("failed to create store")
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14463,
"total_crates": null
} |
fn_clm_storage_impl_get_redis_conn_5187721350787147080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lib
// Implementation of RouterStore<T> for RedisConnInterface
fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
self.cache_store.get_redis_conn()
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 205,
"total_crates": null
} |
fn_clm_storage_impl_diesel_error_to_data_error_5187721350787147080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lib
pub(crate) fn diesel_error_to_data_error(
diesel_error: diesel_models::errors::DatabaseError,
) -> StorageError {
match diesel_error {
diesel_models::errors::DatabaseError::DatabaseConnectionError => {
StorageError::DatabaseConnectionError
}
diesel_models::errors::DatabaseError::NotFound => {
StorageError::ValueNotFound("Value not found".to_string())
}
diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue {
entity: "entity ",
key: None,
},
_ => StorageError::DatabaseError(error_stack::report!(diesel_error)),
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 88,
"total_crates": null
} |
fn_clm_storage_impl_from_config_5187721350787147080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lib
// Inherent implementation for RouterStore<T>
pub async fn from_config(
db_conf: T::Config,
tenant_config: &dyn TenantConfig,
encryption_key: StrongSecret<Vec<u8>>,
cache_store: Arc<RedisStore>,
inmemory_cache_stream: &str,
) -> error_stack::Result<Self, StorageError> {
let db_store = T::new(db_conf, tenant_config, false).await?;
let redis_conn = cache_store.redis_conn.clone();
let cache_store = Arc::new(RedisStore {
redis_conn: Arc::new(RedisConnectionPool::clone(
&redis_conn,
tenant_config.get_redis_key_prefix(),
)),
});
cache_store
.redis_conn
.subscribe(inmemory_cache_stream)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to subscribe to inmemory cache stream")?;
Ok(Self {
db_store,
cache_store,
master_encryption_key: encryption_key,
request_id: None,
})
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 45,
"total_crates": null
} |
fn_clm_storage_impl_find_resources_5187721350787147080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/lib
// Inherent implementation for RouterStore<T>
pub async fn find_resources<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query: R,
) -> error_stack::Result<Vec<D>, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<
Output = error_stack::Result<Vec<M>, diesel_models::errors::DatabaseError>,
> + Send,
M: ReverseConversion<D>,
{
let resource_futures = execute_query
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})?
.into_iter()
.map(|resource| async {
resource
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.collect::<Vec<_>>();
let resources = futures::future::try_join_all(resource_futures).await?;
Ok(resources)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 42,
"total_crates": null
} |
fn_clm_storage_impl_find_by_merchant_id_subscription_id_4234542893022485427 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/subscription
// Implementation of MockDb for SubscriptionInterface
async fn find_by_merchant_id_subscription_id(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_merchant_id: &common_utils::id_type::MerchantId,
_subscription_id: String,
) -> CustomResult<DomainSubscription, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_storage_impl_insert_subscription_entry_4234542893022485427 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/subscription
// Implementation of MockDb for SubscriptionInterface
async fn insert_subscription_entry(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_subscription_new: DomainSubscription,
) -> CustomResult<DomainSubscription, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_update_subscription_entry_4234542893022485427 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/subscription
// Implementation of MockDb for SubscriptionInterface
async fn update_subscription_entry(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_merchant_id: &common_utils::id_type::MerchantId,
_subscription_id: String,
_data: DomainSubscriptionUpdate,
) -> CustomResult<DomainSubscription, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_find_business_profile_by_profile_id_2560645966337275080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/business_profile
// Implementation of MockDb for ProfileInterface
async fn find_business_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
self.business_profiles
.lock()
.await
.iter()
.find(|business_profile| business_profile.get_id() == profile_id)
.cloned()
.async_map(|business_profile| async {
business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for profile_id = {profile_id:?}"
))
.into(),
)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 179,
"total_crates": null
} |
fn_clm_storage_impl_update_profile_by_profile_id_2560645966337275080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/business_profile
// Implementation of MockDb for ProfileInterface
async fn update_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
current_state: domain::Profile,
profile_update: domain::ProfileUpdate,
) -> CustomResult<domain::Profile, StorageError> {
let profile_id = current_state.get_id().to_owned();
self.business_profiles
.lock()
.await
.iter_mut()
.find(|business_profile| business_profile.get_id() == current_state.get_id())
.async_map(|business_profile| async {
let profile_updated = ProfileUpdateInternal::from(profile_update).apply_changeset(
Conversion::convert(current_state)
.await
.change_context(StorageError::EncryptionError)?,
);
*business_profile = profile_updated.clone();
profile_updated
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for profile_id = {profile_id:?}",
))
.into(),
)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_storage_impl_list_profile_by_merchant_id_2560645966337275080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/business_profile
// Implementation of MockDb for ProfileInterface
async fn list_profile_by_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<domain::Profile>, StorageError> {
let business_profiles = self
.business_profiles
.lock()
.await
.iter()
.filter(|business_profile| business_profile.merchant_id == *merchant_id)
.cloned()
.collect::<Vec<_>>();
let mut domain_business_profiles = Vec::with_capacity(business_profiles.len());
for business_profile in business_profiles {
let domain_profile = business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
domain_business_profiles.push(domain_profile);
}
Ok(domain_business_profiles)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 62,
"total_crates": null
} |
fn_clm_storage_impl_find_business_profile_by_merchant_id_profile_id_2560645966337275080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/business_profile
// Implementation of MockDb for ProfileInterface
async fn find_business_profile_by_merchant_id_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
self.business_profiles
.lock()
.await
.iter()
.find(|business_profile| {
business_profile.merchant_id == *merchant_id
&& business_profile.get_id() == profile_id
})
.cloned()
.async_map(|business_profile| async {
business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}"
))
.into(),
)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_storage_impl_find_business_profile_by_profile_name_merchant_id_2560645966337275080 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/business_profile
// Implementation of MockDb for ProfileInterface
async fn find_business_profile_by_profile_name_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<domain::Profile, StorageError> {
self.business_profiles
.lock()
.await
.iter()
.find(|business_profile| {
business_profile.profile_name == profile_name
&& business_profile.merchant_id == *merchant_id
})
.cloned()
.async_map(|business_profile| async {
business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}"
))
.into(),
)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 45,
"total_crates": null
} |
fn_clm_storage_impl_find_invoice_by_invoice_id_-5821899696627931632 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/invoice
// Implementation of MockDb for InvoiceInterface
async fn find_invoice_by_invoice_id(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_invoice_id: String,
) -> CustomResult<DomainInvoice, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 17,
"total_crates": null
} |
fn_clm_storage_impl_find_invoice_by_subscription_id_connector_invoice_id_-5821899696627931632 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/invoice
// Implementation of MockDb for InvoiceInterface
async fn find_invoice_by_subscription_id_connector_invoice_id(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_subscription_id: String,
_connector_invoice_id: common_utils::id_type::InvoiceId,
) -> CustomResult<Option<DomainInvoice>, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 17,
"total_crates": null
} |
fn_clm_storage_impl_insert_invoice_entry_-5821899696627931632 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/invoice
// Implementation of MockDb for InvoiceInterface
async fn insert_invoice_entry(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_invoice_new: DomainInvoice,
) -> CustomResult<DomainInvoice, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_update_invoice_entry_-5821899696627931632 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/invoice
// Implementation of MockDb for InvoiceInterface
async fn update_invoice_entry(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_invoice_id: String,
_data: DomainInvoiceUpdate,
) -> CustomResult<DomainInvoice, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_get_latest_invoice_for_subscription_-5821899696627931632 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/invoice
// Implementation of MockDb for InvoiceInterface
async fn get_latest_invoice_for_subscription(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_subscription_id: String,
) -> CustomResult<DomainInvoice, StorageError> {
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_storage_impl_from_-1583398927825692867 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/errors
// Implementation of HealthCheckDBError for From<diesel::result::Error>
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DBError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2600,
"total_crates": null
} |
fn_clm_storage_impl_is_db_not_found_-1583398927825692867 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/errors
// Inherent implementation for StorageError
pub fn is_db_not_found(&self) -> bool {
match self {
Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound),
Self::ValueNotFound(_) => true,
Self::RedisError(err) => matches!(err.current_context(), RedisError::NotFound),
_ => false,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 186,
"total_crates": null
} |
fn_clm_storage_impl_is_db_unique_violation_-1583398927825692867 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/errors
// Inherent implementation for StorageError
pub fn is_db_unique_violation(&self) -> bool {
match self {
Self::DatabaseError(err) => {
matches!(err.current_context(), DatabaseError::UniqueViolation,)
}
Self::DuplicateValue { .. } => true,
_ => false,
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_storage_impl_to_redis_failed_response_-1583398927825692867 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/errors
// Implementation of error_stack::Report<RedisError> for RedisErrorExt
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError> {
match self.current_context() {
RedisError::NotFound => self.change_context(StorageError::ValueNotFound(format!(
"Data does not exist for key {key}",
))),
RedisError::SetNxFailed | RedisError::SetAddMembersFailed => {
self.change_context(StorageError::DuplicateValue {
entity: "redis",
key: Some(key.to_string()),
})
}
_ => self.change_context(StorageError::KVError),
}
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_storage_impl_find_customer_by_customer_id_merchant_id_1670047021737222443 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/customers
// Implementation of MockDb for domain::CustomerInterface
async fn find_customer_by_customer_id_merchant_id(
&self,
_state: &KeyManagerState,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_storage_impl_list_customers_by_merchant_id_with_count_1670047021737222443 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/customers
// Implementation of MockDb for domain::CustomerInterface
async fn list_customers_by_merchant_id_with_count(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {
let customers = self.customers.lock().await;
let customers_list = try_join_all(
customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.take(usize::from(constraints.limit))
.skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))
.map(|customer| async {
customer
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}),
)
.await?;
let total_count = customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.count();
Ok((customers_list, total_count))
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 54,
"total_crates": null
} |
fn_clm_storage_impl_list_customers_by_merchant_id_1670047021737222443 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/customers
// Implementation of MockDb for domain::CustomerInterface
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, StorageError> {
let customers = self.customers.lock().await;
let customers = try_join_all(
customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.take(usize::from(constraints.limit))
.skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))
.map(|customer| async {
customer
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}),
)
.await?;
Ok(customers)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_storage_impl_find_customer_by_global_id_1670047021737222443 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/customers
// Implementation of MockDb for domain::CustomerInterface
async fn find_customer_by_global_id(
&self,
_state: &KeyManagerState,
_id: &id_type::GlobalCustomerId,
_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 50,
"total_crates": null
} |
fn_clm_storage_impl_insert_customer_1670047021737222443 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/customers
// Implementation of MockDb for domain::CustomerInterface
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let mut customers = self.customers.lock().await;
let customer = Conversion::convert(customer_data)
.await
.change_context(StorageError::EncryptionError)?;
customers.push(customer.clone());
customer
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_storage_impl_new_-1813437614312904270 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/kv_router_store
// Implementation of KVRouterStore<T> for DatabaseStore
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
_test_transaction: bool,
) -> StorageResult<Self> {
let (router_store, _, drainer_num_partitions, ttl_for_kv, soft_kill_mode) = config;
let drainer_stream_name = format!("{}_{}", tenant_config.get_schema(), config.1);
Ok(Self::from_store(
router_store,
drainer_stream_name,
drainer_num_partitions,
ttl_for_kv,
soft_kill_mode,
))
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14455,
"total_crates": null
} |
fn_clm_storage_impl_get_redis_conn_-1813437614312904270 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/kv_router_store
// Implementation of KVRouterStore<T> for RedisConnInterface
fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
self.router_store.get_redis_conn()
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 205,
"total_crates": null
} |
fn_clm_storage_impl_insert_resource_-1813437614312904270 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/kv_router_store
// Inherent implementation for KVRouterStore<T>
pub async fn insert_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
create_resource_fut: R,
resource_new: M,
InsertResourceParams {
insertable,
reverse_lookups,
key,
identifier,
resource_type,
}: InsertResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => create_resource_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
}),
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {
sk_id: identifier.clone(),
pk_id: key_str.clone(),
lookup_id: v,
source: resource_type.to_string(),
updated_by: storage_scheme.to_string(),
};
let results = reverse_lookups
.into_iter()
.map(|v| self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme));
futures::future::try_join_all(results).await?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(insertable),
},
};
match Box::pin(kv_wrapper::<M, _, _>(
self,
KvOperation::<M>::HSetNx(&identifier, &resource_new, redis_entry),
key.clone(),
))
.await
.map_err(|err| err.to_redis_failed_response(&key.to_string()))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: resource_type,
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(resource_new),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 78,
"total_crates": null
} |
fn_clm_storage_impl_update_resource_-1813437614312904270 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/kv_router_store
// Inherent implementation for KVRouterStore<T>
pub async fn update_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
update_resource_fut: R,
updated_resource: M,
UpdateResourceParams {
updateable,
operation,
}: UpdateResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
match operation {
Op::Update(key, field, updated_by) => {
let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(
self,
storage_scheme,
Op::Update(key.clone(), field, updated_by),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
update_resource_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let redis_value = serde_json::to_string(&updated_resource)
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(updateable),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<M>::Hset((field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(errors::StorageError::KVError)?;
Ok(updated_resource)
}
}
}
_ => Err(errors::StorageError::KVError.into()),
}?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 67,
"total_crates": null
} |
fn_clm_storage_impl_filter_resources_-1813437614312904270 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/kv_router_store
// Inherent implementation for KVRouterStore<T>
pub async fn filter_resources<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
filter_resource_db_fut: R,
filter_fn: impl Fn(&M) -> bool,
FilterResourceParams {
key,
pattern,
limit,
}: FilterResourceParams<'_>,
) -> error_stack::Result<Vec<D>, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<Vec<M>, DatabaseError>> + Send,
{
let db_call = || async {
filter_resource_db_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
};
let resources = match storage_scheme {
MerchantStorageScheme::PostgresOnly => db_call().await,
MerchantStorageScheme::RedisKv => {
let redis_fut = async {
let kv_result = Box::pin(kv_wrapper::<M, _, _>(
self,
KvOperation::<M>::Scan(pattern),
key,
))
.await?
.try_into_scan();
kv_result.map(|records| records.into_iter().filter(filter_fn).collect())
};
Box::pin(find_all_combined_kv_database(redis_fut, db_call, limit)).await
}
}?;
let resource_futures = resources
.into_iter()
.map(|pm| async {
pm.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.collect::<Vec<_>>();
futures::future::try_join_all(resource_futures).await
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 65,
"total_crates": null
} |
fn_clm_storage_impl_get_merchant_key_store_by_merchant_id_4266589853430521646 | clm | function | // Repository: hyperswitch
// Crate: storage_impl
// Purpose: Storage backend implementations for database operations
// Module: crates/storage_impl/src/merchant_key_store
// Implementation of MockDb for MerchantKeyStoreInterface
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, StorageError> {
self.merchant_key_store
.lock()
.await
.iter()
.find(|merchant_key| merchant_key.merchant_id == *merchant_id)
.cloned()
.ok_or(StorageError::ValueNotFound(String::from(
"merchant_key_store",
)))?
.convert(state, key, merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError)
}
| {
"crate": "storage_impl",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 243,
"total_crates": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.