repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch | crates/hyperswitch_interfaces/src/api/payments_v2.rs | .rs | //! Payments V2 interface
use hyperswitch_domain_models::{
router_data_v2::PaymentFlowData,
router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken,
PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session,
SetupMandate, Void,
},
router_request_types::{
AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
SdkPaymentsSessionUpdateData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, TaxCalculationResponseData},
};
use crate::api::{
ConnectorCommon, ConnectorIntegrationV2, ConnectorSpecifications, ConnectorValidation,
};
/// trait PaymentAuthorizeV2
pub trait PaymentAuthorizeV2:
ConnectorIntegrationV2<Authorize, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData>
{
}
/// trait PaymentAuthorizeSessionTokenV2
pub trait PaymentAuthorizeSessionTokenV2:
ConnectorIntegrationV2<
AuthorizeSessionToken,
PaymentFlowData,
AuthorizeSessionTokenData,
PaymentsResponseData,
>
{
}
/// trait PaymentSyncV2
pub trait PaymentSyncV2:
ConnectorIntegrationV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
}
/// trait PaymentVoidV2
pub trait PaymentVoidV2:
ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData>
{
}
/// trait PaymentApproveV2
pub trait PaymentApproveV2:
ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData>
{
}
/// trait PaymentRejectV2
pub trait PaymentRejectV2:
ConnectorIntegrationV2<Reject, PaymentFlowData, PaymentsRejectData, PaymentsResponseData>
{
}
/// trait PaymentCaptureV2
pub trait PaymentCaptureV2:
ConnectorIntegrationV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
}
/// trait PaymentSessionV2
pub trait PaymentSessionV2:
ConnectorIntegrationV2<Session, PaymentFlowData, PaymentsSessionData, PaymentsResponseData>
{
}
/// trait MandateSetupV2
pub trait MandateSetupV2:
ConnectorIntegrationV2<SetupMandate, PaymentFlowData, SetupMandateRequestData, PaymentsResponseData>
{
}
/// trait PaymentIncrementalAuthorizationV2
pub trait PaymentIncrementalAuthorizationV2:
ConnectorIntegrationV2<
IncrementalAuthorization,
PaymentFlowData,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>
{
}
///trait TaxCalculationV2
pub trait TaxCalculationV2:
ConnectorIntegrationV2<
CalculateTax,
PaymentFlowData,
PaymentsTaxCalculationData,
TaxCalculationResponseData,
>
{
}
///trait PaymentSessionUpdateV2
pub trait PaymentSessionUpdateV2:
ConnectorIntegrationV2<
SdkSessionUpdate,
PaymentFlowData,
SdkPaymentsSessionUpdateData,
PaymentsResponseData,
>
{
}
///trait PaymentPostSessionTokensV2
pub trait PaymentPostSessionTokensV2:
ConnectorIntegrationV2<
PostSessionTokens,
PaymentFlowData,
PaymentsPostSessionTokensData,
PaymentsResponseData,
>
{
}
/// trait PaymentsCompleteAuthorizeV2
pub trait PaymentsCompleteAuthorizeV2:
ConnectorIntegrationV2<
CompleteAuthorize,
PaymentFlowData,
CompleteAuthorizeData,
PaymentsResponseData,
>
{
}
/// trait PaymentTokenV2
pub trait PaymentTokenV2:
ConnectorIntegrationV2<
PaymentMethodToken,
PaymentFlowData,
PaymentMethodTokenizationData,
PaymentsResponseData,
>
{
}
/// trait ConnectorCustomerV2
pub trait ConnectorCustomerV2:
ConnectorIntegrationV2<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
PaymentsResponseData,
>
{
}
/// trait PaymentsPreProcessingV2
pub trait PaymentsPreProcessingV2:
ConnectorIntegrationV2<
PreProcessing,
PaymentFlowData,
PaymentsPreProcessingData,
PaymentsResponseData,
>
{
}
/// trait PaymentsPostProcessingV2
pub trait PaymentsPostProcessingV2:
ConnectorIntegrationV2<
PostProcessing,
PaymentFlowData,
PaymentsPostProcessingData,
PaymentsResponseData,
>
{
}
/// trait PaymentV2
pub trait PaymentV2:
ConnectorCommon
+ ConnectorSpecifications
+ ConnectorValidation
+ PaymentAuthorizeV2
+ PaymentAuthorizeSessionTokenV2
+ PaymentsCompleteAuthorizeV2
+ PaymentSyncV2
+ PaymentCaptureV2
+ PaymentVoidV2
+ PaymentApproveV2
+ PaymentRejectV2
+ MandateSetupV2
+ PaymentSessionV2
+ PaymentTokenV2
+ PaymentsPreProcessingV2
+ PaymentsPostProcessingV2
+ ConnectorCustomerV2
+ PaymentIncrementalAuthorizationV2
+ TaxCalculationV2
+ PaymentSessionUpdateV2
+ PaymentPostSessionTokensV2
{
}
| 1,170 | 1,005 |
hyperswitch | crates/hyperswitch_interfaces/src/api/disputes.rs | .rs | //! Disputes interface
use hyperswitch_domain_models::{
router_flow_types::dispute::{Accept, Defend, Evidence},
router_request_types::{
AcceptDisputeRequestData, DefendDisputeRequestData, SubmitEvidenceRequestData,
},
router_response_types::{AcceptDisputeResponse, DefendDisputeResponse, SubmitEvidenceResponse},
};
use crate::api::ConnectorIntegration;
/// trait AcceptDispute
pub trait AcceptDispute:
ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>
{
}
/// trait SubmitEvidence
pub trait SubmitEvidence:
ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>
{
}
/// trait DefendDispute
pub trait DefendDispute:
ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>
{
}
/// trait Dispute
pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence + DefendDispute {}
| 203 | 1,006 |
hyperswitch | crates/hyperswitch_interfaces/src/api/authentication.rs | .rs | use hyperswitch_domain_models::{
router_flow_types::authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
router_request_types::authentication::{
ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData,
PreAuthNRequestData,
},
router_response_types::AuthenticationResponseData,
};
use crate::api::ConnectorIntegration;
/// trait ConnectorAuthentication
pub trait ConnectorAuthentication:
ConnectorIntegration<Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData>
{
}
/// trait ConnectorPreAuthentication
pub trait ConnectorPreAuthentication:
ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>
{
}
/// trait ConnectorPreAuthenticationVersionCall
pub trait ConnectorPreAuthenticationVersionCall:
ConnectorIntegration<PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>
{
}
/// trait ConnectorPostAuthentication
pub trait ConnectorPostAuthentication:
ConnectorIntegration<
PostAuthentication,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
>
{
}
/// trait ExternalAuthentication
pub trait ExternalAuthentication:
super::ConnectorCommon
+ ConnectorAuthentication
+ ConnectorPreAuthentication
+ ConnectorPreAuthenticationVersionCall
+ ConnectorPostAuthentication
{
}
| 248 | 1,007 |
hyperswitch | crates/hyperswitch_interfaces/src/api/authentication_v2.rs | .rs | use hyperswitch_domain_models::{
router_data_v2::ExternalAuthenticationFlowData,
router_flow_types::authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
router_request_types::authentication::{
ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData,
PreAuthNRequestData,
},
router_response_types::AuthenticationResponseData,
};
use crate::api::ConnectorIntegrationV2;
/// trait ConnectorAuthenticationV2
pub trait ConnectorAuthenticationV2:
ConnectorIntegrationV2<
Authentication,
ExternalAuthenticationFlowData,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>
{
}
/// trait ConnectorPreAuthenticationV2
pub trait ConnectorPreAuthenticationV2:
ConnectorIntegrationV2<
PreAuthentication,
ExternalAuthenticationFlowData,
PreAuthNRequestData,
AuthenticationResponseData,
>
{
}
/// trait ConnectorPreAuthenticationVersionCallV2
pub trait ConnectorPreAuthenticationVersionCallV2:
ConnectorIntegrationV2<
PreAuthenticationVersionCall,
ExternalAuthenticationFlowData,
PreAuthNRequestData,
AuthenticationResponseData,
>
{
}
/// trait ConnectorPostAuthenticationV2
pub trait ConnectorPostAuthenticationV2:
ConnectorIntegrationV2<
PostAuthentication,
ExternalAuthenticationFlowData,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
>
{
}
/// trait ExternalAuthenticationV2
pub trait ExternalAuthenticationV2:
super::ConnectorCommon
+ ConnectorAuthenticationV2
+ ConnectorPreAuthenticationV2
+ ConnectorPreAuthenticationVersionCallV2
+ ConnectorPostAuthenticationV2
{
}
| 333 | 1,008 |
hyperswitch | crates/hyperswitch_interfaces/src/api/payments.rs | .rs | //! Payments interface
use hyperswitch_domain_models::{
router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken,
PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session,
SetupMandate, Void,
},
router_request_types::{
AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
SdkPaymentsSessionUpdateData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, TaxCalculationResponseData},
};
use crate::api;
/// trait Payment
pub trait Payment:
api::ConnectorCommon
+ api::ConnectorSpecifications
+ api::ConnectorValidation
+ PaymentAuthorize
+ PaymentAuthorizeSessionToken
+ PaymentsCompleteAuthorize
+ PaymentSync
+ PaymentCapture
+ PaymentVoid
+ PaymentApprove
+ PaymentReject
+ MandateSetup
+ PaymentSession
+ PaymentToken
+ PaymentsPreProcessing
+ PaymentsPostProcessing
+ ConnectorCustomer
+ PaymentIncrementalAuthorization
+ PaymentSessionUpdate
+ PaymentPostSessionTokens
{
}
/// trait PaymentSession
pub trait PaymentSession:
api::ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>
{
}
/// trait MandateSetup
pub trait MandateSetup:
api::ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
}
/// trait PaymentAuthorize
pub trait PaymentAuthorize:
api::ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
}
/// trait PaymentCapture
pub trait PaymentCapture:
api::ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>
{
}
/// trait PaymentSync
pub trait PaymentSync:
api::ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>
{
}
/// trait PaymentVoid
pub trait PaymentVoid:
api::ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>
{
}
/// trait PaymentApprove
pub trait PaymentApprove:
api::ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData>
{
}
/// trait PaymentReject
pub trait PaymentReject:
api::ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData>
{
}
/// trait PaymentToken
pub trait PaymentToken:
api::ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
{
}
/// trait PaymentAuthorizeSessionToken
pub trait PaymentAuthorizeSessionToken:
api::ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>
{
}
/// trait PaymentIncrementalAuthorization
pub trait PaymentIncrementalAuthorization:
api::ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>
{
}
/// trait TaxCalculation
pub trait TaxCalculation:
api::ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>
{
}
/// trait SessionUpdate
pub trait PaymentSessionUpdate:
api::ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>
{
}
/// trait PostSessionTokens
pub trait PaymentPostSessionTokens:
api::ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>
{
}
/// trait PaymentsCompleteAuthorize
pub trait PaymentsCompleteAuthorize:
api::ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
{
}
/// trait ConnectorCustomer
pub trait ConnectorCustomer:
api::ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
{
}
/// trait PaymentsPreProcessing
pub trait PaymentsPreProcessing:
api::ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
{
}
/// trait PaymentsPostProcessing
pub trait PaymentsPostProcessing:
api::ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>
{
}
| 906 | 1,009 |
hyperswitch | crates/hyperswitch_interfaces/src/api/payouts_v2.rs | .rs | //! Payouts V2 interface
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::PayoutFlowData,
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
use super::ConnectorCommon;
use crate::api::ConnectorIntegrationV2;
/// trait PayoutCancelV2
pub trait PayoutCancelV2:
ConnectorIntegrationV2<PoCancel, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutCreateV2
pub trait PayoutCreateV2:
ConnectorIntegrationV2<PoCreate, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutEligibilityV2
pub trait PayoutEligibilityV2:
ConnectorIntegrationV2<PoEligibility, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutFulfillV2
pub trait PayoutFulfillV2:
ConnectorIntegrationV2<PoFulfill, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutQuoteV2
pub trait PayoutQuoteV2:
ConnectorIntegrationV2<PoQuote, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutRecipientV2
pub trait PayoutRecipientV2:
ConnectorIntegrationV2<PoRecipient, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutRecipientAccountV2
pub trait PayoutRecipientAccountV2:
ConnectorIntegrationV2<PoRecipientAccount, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutSyncV2
pub trait PayoutSyncV2:
ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
#[cfg(feature = "payouts")]
/// trait Payouts
pub trait PayoutsV2:
ConnectorCommon
+ PayoutCancelV2
+ PayoutCreateV2
+ PayoutEligibilityV2
+ PayoutFulfillV2
+ PayoutQuoteV2
+ PayoutRecipientV2
+ PayoutRecipientAccountV2
+ PayoutSyncV2
{
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait PayoutsV2 {}
| 590 | 1,010 |
hyperswitch | crates/hyperswitch_interfaces/src/api/revenue_recovery.rs | .rs | //! Revenue Recovery Interface
use hyperswitch_domain_models::{
router_flow_types::{BillingConnectorPaymentsSync, RecoveryRecordBack},
router_request_types::revenue_recovery::{
BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest,
},
router_response_types::revenue_recovery::{
BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse,
},
};
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use super::ConnectorCommon;
use super::ConnectorIntegration;
/// trait RevenueRecovery
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
pub trait RevenueRecovery:
ConnectorCommon + BillingConnectorPaymentsSyncIntegration + RevenueRecoveryRecordBack
{
}
/// trait BillingConnectorPaymentsSyncIntegration
pub trait BillingConnectorPaymentsSyncIntegration:
ConnectorIntegration<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>
{
}
/// trait RevenueRecoveryRecordBack
pub trait RevenueRecoveryRecordBack:
ConnectorIntegration<
RecoveryRecordBack,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
>
{
}
#[cfg(not(all(feature = "v2", feature = "revenue_recovery")))]
/// trait RevenueRecovery
pub trait RevenueRecovery {}
| 269 | 1,011 |
hyperswitch | crates/hyperswitch_interfaces/src/api/files_v2.rs | .rs | //! Files V2 interface
use hyperswitch_domain_models::{
router_data_v2::FilesFlowData,
router_flow_types::{Retrieve, Upload},
router_request_types::{RetrieveFileRequestData, UploadFileRequestData},
router_response_types::{RetrieveFileResponse, UploadFileResponse},
};
use crate::api::{errors, files::FilePurpose, ConnectorCommon, ConnectorIntegrationV2};
/// trait UploadFileV2
pub trait UploadFileV2:
ConnectorIntegrationV2<Upload, FilesFlowData, UploadFileRequestData, UploadFileResponse>
{
}
/// trait RetrieveFileV2
pub trait RetrieveFileV2:
ConnectorIntegrationV2<Retrieve, FilesFlowData, RetrieveFileRequestData, RetrieveFileResponse>
{
}
/// trait FileUploadV2
pub trait FileUploadV2: ConnectorCommon + Sync + UploadFileV2 + RetrieveFileV2 {
/// fn validate_file_upload_v2
fn validate_file_upload_v2(
&self,
_purpose: FilePurpose,
_file_size: i32,
_file_type: mime::Mime,
) -> common_utils::errors::CustomResult<(), errors::ConnectorError> {
Err(errors::ConnectorError::FileValidationFailed {
reason: "".to_owned(),
}
.into())
}
}
| 274 | 1,012 |
hyperswitch | crates/hyperswitch_interfaces/src/api/disputes_v2.rs | .rs | //! Disputes V2 interface
use hyperswitch_domain_models::{
router_data_v2::DisputesFlowData,
router_flow_types::dispute::{Accept, Defend, Evidence},
router_request_types::{
AcceptDisputeRequestData, DefendDisputeRequestData, SubmitEvidenceRequestData,
},
router_response_types::{AcceptDisputeResponse, DefendDisputeResponse, SubmitEvidenceResponse},
};
use crate::api::ConnectorIntegrationV2;
/// trait AcceptDisputeV2
pub trait AcceptDisputeV2:
ConnectorIntegrationV2<Accept, DisputesFlowData, AcceptDisputeRequestData, AcceptDisputeResponse>
{
}
/// trait SubmitEvidenceV2
pub trait SubmitEvidenceV2:
ConnectorIntegrationV2<
Evidence,
DisputesFlowData,
SubmitEvidenceRequestData,
SubmitEvidenceResponse,
>
{
}
/// trait DefendDisputeV2
pub trait DefendDisputeV2:
ConnectorIntegrationV2<Defend, DisputesFlowData, DefendDisputeRequestData, DefendDisputeResponse>
{
}
/// trait DisputeV2
pub trait DisputeV2:
super::ConnectorCommon + AcceptDisputeV2 + SubmitEvidenceV2 + DefendDisputeV2
{
}
| 273 | 1,013 |
hyperswitch | crates/hyperswitch_interfaces/src/api/refunds.rs | .rs | //! Refunds interface
use hyperswitch_domain_models::{
router_flow_types::{Execute, RSync},
router_request_types::RefundsData,
router_response_types::RefundsResponseData,
};
use crate::api::{self, ConnectorCommon};
/// trait RefundExecute
pub trait RefundExecute:
api::ConnectorIntegration<Execute, RefundsData, RefundsResponseData>
{
}
/// trait RefundSync
pub trait RefundSync: api::ConnectorIntegration<RSync, RefundsData, RefundsResponseData> {}
/// trait Refund
pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {}
| 133 | 1,014 |
hyperswitch | crates/hyperswitch_interfaces/src/api/fraud_check.rs | .rs | //! FRM interface
use hyperswitch_domain_models::{
router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use crate::api::ConnectorIntegration;
/// trait FraudCheckSale
pub trait FraudCheckSale:
ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData>
{
}
/// trait FraudCheckCheckout
pub trait FraudCheckCheckout:
ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>
{
}
/// trait FraudCheckTransaction
pub trait FraudCheckTransaction:
ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>
{
}
/// trait FraudCheckFulfillment
pub trait FraudCheckFulfillment:
ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
{
}
/// trait FraudCheckRecordReturn
pub trait FraudCheckRecordReturn:
ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>
{
}
/// trait FraudCheck
pub trait FraudCheck:
super::ConnectorCommon
+ FraudCheckSale
+ FraudCheckTransaction
+ FraudCheckCheckout
+ FraudCheckFulfillment
+ FraudCheckRecordReturn
{
}
| 305 | 1,015 |
hyperswitch | crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs | .rs | //! FRM V2 interface
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::FrmFlowData,
router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use crate::api::ConnectorIntegrationV2;
/// trait FraudCheckSaleV2
pub trait FraudCheckSaleV2:
ConnectorIntegrationV2<Sale, FrmFlowData, FraudCheckSaleData, FraudCheckResponseData>
{
}
/// trait FraudCheckCheckoutV2
pub trait FraudCheckCheckoutV2:
ConnectorIntegrationV2<Checkout, FrmFlowData, FraudCheckCheckoutData, FraudCheckResponseData>
{
}
/// trait FraudCheckTransactionV2
pub trait FraudCheckTransactionV2:
ConnectorIntegrationV2<Transaction, FrmFlowData, FraudCheckTransactionData, FraudCheckResponseData>
{
}
/// trait FraudCheckFulfillmentV2
pub trait FraudCheckFulfillmentV2:
ConnectorIntegrationV2<Fulfillment, FrmFlowData, FraudCheckFulfillmentData, FraudCheckResponseData>
{
}
/// trait FraudCheckRecordReturnV2
pub trait FraudCheckRecordReturnV2:
ConnectorIntegrationV2<
RecordReturn,
FrmFlowData,
FraudCheckRecordReturnData,
FraudCheckResponseData,
>
{
}
/// trait FraudCheckV2
pub trait FraudCheckV2:
super::ConnectorCommon
+ FraudCheckSaleV2
+ FraudCheckTransactionV2
+ FraudCheckCheckoutV2
+ FraudCheckFulfillmentV2
+ FraudCheckRecordReturnV2
{
}
| 393 | 1,016 |
hyperswitch | crates/hyperswitch_interfaces/src/api/payouts.rs | .rs | //! Payouts interface
use hyperswitch_domain_models::{
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
use super::ConnectorCommon;
use crate::api::ConnectorIntegration;
/// trait PayoutCancel
pub trait PayoutCancel: ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> {}
/// trait PayoutCreate
pub trait PayoutCreate: ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> {}
/// trait PayoutEligibility
pub trait PayoutEligibility:
ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutFulfill
pub trait PayoutFulfill: ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> {}
/// trait PayoutQuote
pub trait PayoutQuote: ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> {}
/// trait PayoutRecipient
pub trait PayoutRecipient:
ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutRecipientAccount
pub trait PayoutRecipientAccount:
ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutSync
pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {}
#[cfg(feature = "payouts")]
/// trait Payouts
pub trait Payouts:
ConnectorCommon
+ PayoutCancel
+ PayoutCreate
+ PayoutEligibility
+ PayoutFulfill
+ PayoutQuote
+ PayoutRecipient
+ PayoutRecipientAccount
+ PayoutSync
{
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait Payouts {}
| 453 | 1,017 |
hyperswitch | crates/hyperswitch_interfaces/src/api/refunds_v2.rs | .rs | //! Refunds V2 interface
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::RefundFlowData,
router_flow_types::refunds::{Execute, RSync},
router_request_types::RefundsData,
router_response_types::RefundsResponseData,
};
use crate::api::{ConnectorCommon, ConnectorIntegrationV2};
/// trait RefundExecuteV2
pub trait RefundExecuteV2:
ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData>
{
}
/// trait RefundSyncV2
pub trait RefundSyncV2:
ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData>
{
}
/// trait RefundV2
pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {}
| 184 | 1,018 |
hyperswitch | crates/hyperswitch_interfaces/src/api/files.rs | .rs | //! 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())
}
}
| 289 | 1,019 |
hyperswitch | crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs | .rs | //! Module containing trait for raw secret retrieval
use common_utils::errors::CustomResult;
use crate::secrets_interface::{
secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
SecretManagementInterface, SecretsManagementError,
};
/// Trait defining the interface for retrieving a raw secret value, given a secured value
#[async_trait::async_trait]
pub trait SecretsHandler
where
Self: Sized,
{
/// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret`
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
kms_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>;
}
| 161 | 1,020 |
hyperswitch | crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs | .rs | //! Module to manage encrypted and decrypted states for a given type.
use std::marker::PhantomData;
use serde::{Deserialize, Deserializer};
/// Trait defining the states of a secret
pub trait SecretState {}
/// Decrypted state
#[derive(Debug, Clone, Deserialize, Default)]
pub struct RawSecret {}
/// Encrypted state
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SecuredSecret {}
impl SecretState for RawSecret {}
impl SecretState for SecuredSecret {}
/// Struct for managing the encrypted and decrypted states of a given type
#[derive(Debug, Clone, Default)]
pub struct SecretStateContainer<T, S: SecretState> {
inner: T,
marker: PhantomData<S>,
}
impl<T: Clone, S: SecretState> SecretStateContainer<T, S> {
/// Get the inner data while consuming self
#[inline]
pub fn into_inner(self) -> T {
self.inner
}
/// Get the reference to inner value
#[inline]
pub fn get_inner(&self) -> &T {
&self.inner
}
}
impl<'de, T: Deserialize<'de>, S: SecretState> Deserialize<'de> for SecretStateContainer<T, S> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let val = Deserialize::deserialize(deserializer)?;
Ok(Self {
inner: val,
marker: PhantomData,
})
}
}
impl<T> SecretStateContainer<T, SecuredSecret> {
/// Transition the secret state from `SecuredSecret` to `RawSecret`
pub fn transition_state(
mut self,
decryptor_fn: impl FnOnce(T) -> T,
) -> SecretStateContainer<T, RawSecret> {
self.inner = decryptor_fn(self.inner);
SecretStateContainer {
inner: self.inner,
marker: PhantomData,
}
}
}
| 415 | 1,021 |
hyperswitch | crates/storage_impl/Cargo.toml | .toml | [package]
name = "storage_impl"
description = "Storage backend implementations for data structures in router"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
default = ["olap", "oltp"]
dynamic_routing = []
oltp = []
olap = ["hyperswitch_domain_models/olap"]
payouts = ["hyperswitch_domain_models/payouts"]
v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "common_utils/v1"]
v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "common_utils/v2"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"]
payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"]
refunds_v2 = ["diesel_models/refunds_v2"]
[dependencies]
# First Party dependencies
api_models = { version = "0.1.0", path = "../api_models" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
diesel_models = { version = "0.1.0", path = "../diesel_models", default-features = false }
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
router_derive = { version = "0.1.0", path = "../router_derive" }
router_env = { version = "0.1.0", path = "../router_env" }
# Third party crates
async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" }
async-trait = "0.1.79"
bb8 = "0.8.3"
bytes = "1.6.0"
config = { version = "0.14.0", features = ["toml"] }
crc32fast = "1.4.0"
diesel = { version = "2.2.3", default-features = false, features = ["postgres"] }
dyn-clone = "1.0.17"
error-stack = "0.4.1"
futures = "0.3.30"
moka = { version = "0.12", features = ["future"] }
once_cell = "1.19.0"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
thiserror = "1.0.58"
tokio = { version = "1.37.0", features = ["rt-multi-thread"] }
[lints]
workspace = true
| 743 | 1,022 |
hyperswitch | crates/storage_impl/README.md | .md | # Storage implementations
Storage backend implementations for data structures & objects.
| 13 | 1,023 |
hyperswitch | crates/storage_impl/src/mock_db.rs | .rs | use std::sync::Arc;
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use diesel_models as store;
use error_stack::ResultExt;
use futures::lock::{Mutex, MutexGuard};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
payments::{payment_attempt::PaymentAttempt, PaymentIntent},
};
use redis_interface::RedisSettings;
use crate::{errors::StorageError, redis::RedisStore};
pub mod payment_attempt;
pub mod payment_intent;
#[cfg(feature = "payouts")]
pub mod payout_attempt;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod redis_conn;
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
#[derive(Clone)]
pub struct MockDb {
pub addresses: Arc<Mutex<Vec<store::Address>>>,
pub configs: Arc<Mutex<Vec<store::Config>>>,
pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>,
pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>,
pub payment_attempts: Arc<Mutex<Vec<PaymentAttempt>>>,
pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>,
pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>,
pub customers: Arc<Mutex<Vec<store::Customer>>>,
pub refunds: Arc<Mutex<Vec<store::Refund>>>,
pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>,
pub redis: Arc<RedisStore>,
pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,
pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,
pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>,
pub events: Arc<Mutex<Vec<store::Event>>>,
pub disputes: Arc<Mutex<Vec<store::Dispute>>>,
pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>,
pub mandates: Arc<Mutex<Vec<store::Mandate>>>,
pub captures: Arc<Mutex<Vec<store::capture::Capture>>>,
pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>,
pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>,
pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>,
pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>,
pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>,
pub users: Arc<Mutex<Vec<store::user::User>>>,
pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>,
pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>,
pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>,
#[cfg(feature = "payouts")]
pub payout_attempt: Arc<Mutex<Vec<store::payout_attempt::PayoutAttempt>>>,
#[cfg(feature = "payouts")]
pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>,
pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>,
pub roles: Arc<Mutex<Vec<store::role::Role>>>,
pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,
pub user_authentication_methods:
Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>,
pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>,
}
impl 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(),
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(),
})
}
pub async fn find_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,
{
let resource = resources.iter().find(filter_fn).cloned();
match resource {
Some(res) => Ok(res
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?),
None => Err(StorageError::ValueNotFound(error_message).into()),
}
}
pub async fn find_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)
}
}
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())
}
}
}
#[cfg(not(feature = "payouts"))]
impl PayoutsInterface for MockDb {}
#[cfg(not(feature = "payouts"))]
impl PayoutAttemptInterface for MockDb {}
| 1,798 | 1,024 |
hyperswitch | crates/storage_impl/src/metrics.rs | .rs | use router_env::{counter_metric, gauge_metric, global_meter};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses
// Metrics for KV
counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER);
counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER);
counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER);
counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER);
counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER);
// Metrics for In-memory cache
gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER);
| 175 | 1,025 |
hyperswitch | crates/storage_impl/src/refund.rs | .rs | use diesel_models::refund::Refund;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for Refund {}
| 30 | 1,026 |
hyperswitch | crates/storage_impl/src/connection.rs | .rs | use bb8::PooledConnection;
use common_utils::errors;
use diesel::PgConnection;
use error_stack::ResultExt;
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
/// Creates a Redis connection pool for the specified Redis settings
/// # Panics
///
/// Panics if failed to create a redis pool
#[allow(clippy::expect_used)]
pub async fn redis_connection(
redis: &redis_interface::RedisSettings,
) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(redis)
.await
.expect("Failed to create Redis Connection Pool")
}
pub async fn pg_connection_read<T: crate::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
crate::errors::StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_master_pool();
pool.get()
.await
.change_context(crate::errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_connection_write<T: crate::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
crate::errors::StorageError,
> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
pool.get()
.await
.change_context(crate::errors::StorageError::DatabaseConnectionError)
}
| 497 | 1,027 |
hyperswitch | crates/storage_impl/src/lookup.rs | .rs | use common_utils::errors::CustomResult;
use diesel_models::{
enums as storage_enums, kv,
reverse_lookup::{
ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew,
},
};
use error_stack::ResultExt;
use redis_interface::SetnxReply;
use crate::{
diesel_error_to_data_error,
errors::{self, RedisErrorExt},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, try_redis_get_else_try_database_get},
DatabaseStore, RouterStore,
};
#[async_trait::async_trait]
pub trait ReverseLookupInterface {
async fn insert_reverse_lookup(
&self,
_new: DieselReverseLookupNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError>;
async fn get_lookup_by_lookup_id(
&self,
_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError>;
}
#[async_trait::async_trait]
impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> {
async fn insert_reverse_lookup(
&self,
new: DieselReverseLookupNew,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let conn = self
.get_master_pool()
.get()
.await
.change_context(errors::StorageError::DatabaseConnectionError)?;
new.insert(&conn).await.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
async fn get_lookup_by_lookup_id(
&self,
id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let conn = utils::pg_connection_read(self).await?;
DieselReverseLookup::find_by_lookup_id(id, &conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
async fn insert_reverse_lookup(
&self,
new: DieselReverseLookupNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_reverse_lookup(new, storage_scheme)
.await
}
storage_enums::MerchantStorageScheme::RedisKv => {
let created_rev_lookup = DieselReverseLookup {
lookup_id: new.lookup_id.clone(),
sk_id: new.sk_id.clone(),
pk_id: new.pk_id.clone(),
source: new.source.clone(),
updated_by: storage_scheme.to_string(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
},
};
match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>(
self,
KvOperation::SetNx(&created_rev_lookup, redis_entry),
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id),
},
))
.await
.map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))?
.try_into_setnx()
{
Ok(SetnxReply::KeySet) => Ok(created_rev_lookup),
Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "reverse_lookup",
key: Some(created_rev_lookup.lookup_id.clone()),
}
.into()),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
async fn get_lookup_by_lookup_id(
&self,
id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let database_call = || async {
self.router_store
.get_lookup_by_lookup_id(id, storage_scheme)
.await
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await,
storage_enums::MerchantStorageScheme::RedisKv => {
let redis_fut = async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselReverseLookup>::Get,
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{id}"),
},
))
.await?
.try_into_get()
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
database_call,
))
.await
}
}
}
}
| 1,183 | 1,028 |
hyperswitch | crates/storage_impl/src/payments.rs | .rs | pub mod payment_attempt;
pub mod payment_intent;
use diesel_models::{payment_attempt::PaymentAttempt, PaymentIntent};
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for PaymentIntent {}
impl KvStorePartition for PaymentAttempt {}
| 52 | 1,029 |
hyperswitch | crates/storage_impl/src/address.rs | .rs | use diesel_models::address::Address;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for Address {}
| 28 | 1,030 |
hyperswitch | crates/storage_impl/src/callback_mapper.rs | .rs | use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper;
use hyperswitch_domain_models::callback_mapper::CallbackMapper;
use crate::DataModelExt;
impl DataModelExt for CallbackMapper {
type StorageModel = DieselCallbackMapper;
fn to_storage_model(self) -> Self::StorageModel {
DieselCallbackMapper {
id: self.id,
type_: self.type_,
data: self.data,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
id: storage_model.id,
type_: storage_model.type_,
data: storage_model.data,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
}
}
}
| 173 | 1,031 |
hyperswitch | crates/storage_impl/src/database.rs | .rs | pub mod store;
| 4 | 1,032 |
hyperswitch | crates/storage_impl/src/utils.rs | .rs | use bb8::PooledConnection;
use diesel::PgConnection;
use error_stack::ResultExt;
use crate::{
errors::{RedisErrorExt, StorageError},
metrics, DatabaseStore,
};
pub async fn pg_connection_read<T: DatabaseStore>(
store: &T,
) -> error_stack::Result<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_master_pool();
pool.get()
.await
.change_context(StorageError::DatabaseConnectionError)
}
pub async fn pg_connection_write<T: DatabaseStore>(
store: &T,
) -> error_stack::Result<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
StorageError,
> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
pool.get()
.await
.change_context(StorageError::DatabaseConnectionError)
}
pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(
redis_fut: RFut,
database_call_closure: F,
) -> error_stack::Result<T, StorageError>
where
F: FnOnce() -> DFut,
RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>,
DFut: futures::Future<Output = error_stack::Result<T, StorageError>>,
{
let redis_output = redis_fut.await;
match redis_output {
Ok(output) => Ok(output),
Err(redis_error) => match redis_error.current_context() {
redis_interface::errors::RedisError::NotFound => {
metrics::KV_MISS.add(1, &[]);
database_call_closure().await
}
// Keeping the key empty here since the error would never go here.
_ => Err(redis_error.to_redis_failed_response("")),
},
}
}
use std::collections::HashSet;
use crate::UniqueConstraints;
fn union_vec<T>(mut kv_rows: Vec<T>, sql_rows: Vec<T>) -> Vec<T>
where
T: UniqueConstraints,
{
let mut kv_unique_keys = HashSet::new();
kv_rows.iter().for_each(|v| {
kv_unique_keys.insert(v.unique_constraints().concat());
});
sql_rows.into_iter().for_each(|v| {
let unique_key = v.unique_constraints().concat();
if !kv_unique_keys.contains(&unique_key) {
kv_rows.push(v);
}
});
kv_rows
}
pub async fn find_all_combined_kv_database<F, RFut, DFut, T>(
redis_fut: RFut,
database_call: F,
limit: Option<i64>,
) -> error_stack::Result<Vec<T>, StorageError>
where
T: UniqueConstraints,
F: FnOnce() -> DFut,
RFut:
futures::Future<Output = error_stack::Result<Vec<T>, redis_interface::errors::RedisError>>,
DFut: futures::Future<Output = error_stack::Result<Vec<T>, StorageError>>,
{
let trunc = |v: &mut Vec<_>| {
if let Some(l) = limit.and_then(|v| TryInto::try_into(v).ok()) {
v.truncate(l);
}
};
let limit_satisfies = |len: usize, limit: i64| {
TryInto::try_into(limit)
.ok()
.map_or(true, |val: usize| len >= val)
};
let redis_output = redis_fut.await;
match (redis_output, limit) {
(Ok(mut kv_rows), Some(lim)) if limit_satisfies(kv_rows.len(), lim) => {
trunc(&mut kv_rows);
Ok(kv_rows)
}
(Ok(kv_rows), _) => database_call().await.map(|db_rows| {
let mut res = union_vec(kv_rows, db_rows);
trunc(&mut res);
res
}),
(Err(redis_error), _) => match redis_error.current_context() {
redis_interface::errors::RedisError::NotFound => {
metrics::KV_MISS.add(1, &[]);
database_call().await
}
// Keeping the key empty here since the error would never go here.
_ => Err(redis_error.to_redis_failed_response("")),
},
}
}
| 1,082 | 1,033 |
hyperswitch | crates/storage_impl/src/config.rs | .rs | use common_utils::{id_type, DbConnectionParams};
use masking::Secret;
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
pub queue_strategy: QueueStrategy,
pub min_idle: Option<u32>,
pub max_lifetime: Option<u64>,
}
impl DbConnectionParams for Database {
fn get_username(&self) -> &str {
&self.username
}
fn get_password(&self) -> Secret<String> {
self.password.clone()
}
fn get_host(&self) -> &str {
&self.host
}
fn get_port(&self) -> u16 {
self.port
}
fn get_dbname(&self) -> &str {
&self.dbname
}
}
pub trait TenantConfig: Send + Sync {
fn get_tenant_id(&self) -> &id_type::TenantId;
fn get_schema(&self) -> &str;
fn get_accounts_schema(&self) -> &str;
fn get_redis_key_prefix(&self) -> &str;
fn get_clickhouse_database(&self) -> &str;
}
#[derive(Debug, serde::Deserialize, Clone, Copy, Default)]
#[serde(rename_all = "PascalCase")]
pub enum QueueStrategy {
#[default]
Fifo,
Lifo,
}
impl From<QueueStrategy> for bb8::QueueStrategy {
fn from(value: QueueStrategy) -> Self {
match value {
QueueStrategy::Fifo => Self::Fifo,
QueueStrategy::Lifo => Self::Lifo,
}
}
}
impl Default for Database {
fn default() -> Self {
Self {
username: String::new(),
password: Secret::<String>::default(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
queue_strategy: QueueStrategy::default(),
min_idle: None,
max_lifetime: None,
}
}
}
| 482 | 1,034 |
hyperswitch | crates/storage_impl/src/kv_router_store.rs | .rs | use std::{fmt::Debug, sync::Arc};
use common_enums::enums::MerchantStorageScheme;
use common_utils::{fallback_reverse_lookup_not_found, types::keymanager::KeyManagerState};
use diesel_models::{errors::DatabaseError, kv};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::StrongSecret;
use redis_interface::{errors::RedisError, types::HsetnxReply, RedisConnectionPool};
use router_env::logger;
use serde::de;
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
use crate::{
config::TenantConfig,
database::store::PgPool,
diesel_error_to_data_error,
errors::{self, RedisErrorExt, StorageResult},
lookup::ReverseLookupInterface,
metrics,
redis::kv_store::{
decide_storage_scheme, kv_wrapper, KvOperation, KvStorePartition, Op, PartitionKey,
RedisConnInterface,
},
utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get},
RouterStore, UniqueConstraints,
};
pub use crate::{database::store::DatabaseStore, mock_db::MockDb};
#[derive(Debug, Clone)]
pub struct KVRouterStore<T: DatabaseStore> {
pub router_store: RouterStore<T>,
drainer_stream_name: String,
drainer_num_partitions: u8,
pub ttl_for_kv: u32,
pub request_id: Option<String>,
pub soft_kill_mode: bool,
}
pub struct InsertResourceParams<'a> {
pub insertable: kv::Insertable,
pub reverse_lookups: Vec<String>,
pub key: PartitionKey<'a>,
// secondary key
pub identifier: String,
// type of resource Eg: "payment_attempt"
pub resource_type: &'static str,
}
pub struct UpdateResourceParams<'a> {
pub updateable: kv::Updateable,
pub operation: Op<'a>,
}
pub struct FilterResourceParams<'a> {
pub key: PartitionKey<'a>,
pub pattern: &'static str,
pub limit: Option<i64>,
}
pub enum FindResourceBy<'a> {
Id(String, PartitionKey<'a>),
LookupId(String),
}
pub trait DomainType: Debug + Sync + Conversion {}
impl<T: Debug + Sync + Conversion> DomainType for T {}
/// Storage model with all required capabilities for KV operations
pub trait StorageModel<D: Conversion>:
de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync
+ Send
+ ReverseConversion<D>
{
}
impl<T, D> StorageModel<D> for T
where
T: de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync
+ Send
+ ReverseConversion<D>,
D: DomainType,
{
}
#[async_trait::async_trait]
impl<T> DatabaseStore for KVRouterStore<T>
where
RouterStore<T>: DatabaseStore,
T: DatabaseStore,
{
type Config = (RouterStore<T>, String, u8, u32, Option<bool>);
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
_test_transaction: bool,
) -> 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,
))
}
fn get_master_pool(&self) -> &PgPool {
self.router_store.get_master_pool()
}
fn get_replica_pool(&self) -> &PgPool {
self.router_store.get_replica_pool()
}
fn get_accounts_master_pool(&self) -> &PgPool {
self.router_store.get_accounts_master_pool()
}
fn get_accounts_replica_pool(&self) -> &PgPool {
self.router_store.get_accounts_replica_pool()
}
}
impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> {
fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
self.router_store.get_redis_conn()
}
}
impl<T: DatabaseStore> KVRouterStore<T> {
pub fn from_store(
store: RouterStore<T>,
drainer_stream_name: String,
drainer_num_partitions: u8,
ttl_for_kv: u32,
soft_kill: Option<bool>,
) -> Self {
let request_id = store.request_id.clone();
Self {
router_store: store,
drainer_stream_name,
drainer_num_partitions,
ttl_for_kv,
request_id,
soft_kill_mode: soft_kill.unwrap_or(false),
}
}
pub fn master_key(&self) -> &StrongSecret<Vec<u8>> {
self.router_store.master_key()
}
pub fn get_drainer_stream_name(&self, shard_key: &str) -> String {
format!("{{{}}}_{}", shard_key, self.drainer_stream_name)
}
pub async fn push_to_drainer_stream<R>(
&self,
redis_entry: kv::TypedSql,
partition_key: PartitionKey<'_>,
) -> error_stack::Result<(), RedisError>
where
R: KvStorePartition,
{
let global_id = format!("{}", partition_key);
let request_id = self.request_id.clone().unwrap_or_default();
let shard_key = R::shard_key(partition_key, self.drainer_num_partitions);
let stream_name = self.get_drainer_stream_name(&shard_key);
self.router_store
.cache_store
.redis_conn
.stream_append_entry(
&stream_name.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
redis_entry
.to_field_value_pairs(request_id, global_id)
.change_context(RedisError::JsonSerializationFailed)?,
)
.await
.map(|_| metrics::KV_PUSHED_TO_DRAINER.add(1, &[]))
.inspect_err(|error| {
metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(1, &[]);
logger::error!(?error, "Failed to add entry in drainer stream");
})
.change_context(RedisError::StreamAppendFailed)
}
pub async fn find_resource_by_id<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
find_resource_db_fut: R,
find_by: FindResourceBy<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: DomainType,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
let database_call = || async {
find_resource_db_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<T, M>(
self,
storage_scheme,
Op::Find,
))
.await;
let res = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let (field, key) = match find_by {
FindResourceBy::Id(field, key) => (field, key),
FindResourceBy::LookupId(lookup_id) => {
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
(
lookup.clone().sk_id,
PartitionKey::CombinationKey {
combination: &lookup.clone().pk_id,
},
)
}
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
};
res()
.await?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
pub async fn find_optional_resource_by_id<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
find_resource_db_fut: R,
find_by: FindResourceBy<'_>,
) -> error_stack::Result<Option<D>, errors::StorageError>
where
D: DomainType,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<Option<M>, DatabaseError>> + Send,
{
let database_call = || async {
find_resource_db_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<T, M>(
self,
storage_scheme,
Op::Find,
))
.await;
let res = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let (field, key) = match find_by {
FindResourceBy::Id(field, key) => (field, key),
FindResourceBy::LookupId(lookup_id) => {
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
(
lookup.clone().sk_id,
PartitionKey::CombinationKey {
combination: &lookup.clone().pk_id,
},
)
}
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key))
.await?
.try_into_hget()
.map(Some)
},
database_call,
))
.await
}
}
};
match res().await? {
Some(resource) => Ok(Some(
resource
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
)),
None => Ok(None),
}
}
pub async fn insert_resource<D, R, M>(
&self,
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)
}
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)
}
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
}
}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {}
| 3,910 | 1,035 |
hyperswitch | crates/storage_impl/src/customers.rs | .rs | use diesel_models::customers::Customer;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for Customer {}
| 28 | 1,036 |
hyperswitch | crates/storage_impl/src/payment_method.rs | .rs | use diesel_models::payment_method::PaymentMethod;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for PaymentMethod {}
use common_enums::enums::MerchantStorageScheme;
use common_utils::{errors::CustomResult, id_type, types::keymanager::KeyManagerState};
use diesel_models::{
kv,
payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface},
};
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
diesel_error_to_data_error, errors,
kv_router_store::{
FilterResourceParams, FindResourceBy, InsertResourceParams, KVRouterStore,
UpdateResourceParams,
},
redis::kv_store::{Op, PartitionKey},
utils::{pg_connection_read, pg_connection_write},
DatabaseStore, RouterStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
type Error = errors::StorageError;
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resource_by_id(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_payment_method_id(&conn, payment_method_id),
FindResourceBy::LookupId(format!("payment_method_{}", payment_method_id)),
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
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 conn = pg_connection_read(self).await?;
self.find_resource_by_id(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_id(&conn, payment_method_id),
FindResourceBy::LookupId(format!(
"payment_method_{}",
payment_method_id.get_string_repr()
)),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resource_by_id(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_locker_id(&conn, locker_id),
FindResourceBy::LookupId(format!("payment_method_locker_{}", locker_id)),
)
.await
}
// not supported in kv
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
.get_payment_method_count_by_customer_id_merchant_id_status(
customer_id,
merchant_id,
status,
)
.await
}
#[instrument(skip_all)]
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
.get_payment_method_count_by_merchant_id_status(merchant_id, status)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.insert_payment_method(state, key_store, payment_method, storage_scheme)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_write(self).await?;
let mut payment_method_new = payment_method
.construct_new()
.await
.change_context(errors::StorageError::DecryptionError)?;
payment_method_new.update_storage_scheme(storage_scheme);
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &payment_method_new.merchant_id.clone(),
customer_id: &payment_method_new.customer_id.clone(),
};
let identifier = format!("payment_method_id_{}", payment_method_new.get_id());
let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id());
let mut reverse_lookups = vec![lookup_id1];
if let Some(locker_id) = &payment_method_new.locker_id {
reverse_lookups.push(format!("payment_method_locker_{}", locker_id))
}
let payment_method = (&payment_method_new.clone()).into();
self.insert_resource(
state,
key_store,
storage_scheme,
payment_method_new.clone().insert(&conn),
payment_method,
InsertResourceParams {
insertable: kv::Insertable::PaymentMethod(payment_method_new.clone()),
reverse_lookups,
key,
identifier,
resource_type: "payment_method",
},
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
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 = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let merchant_id = payment_method.merchant_id.clone();
let customer_id = payment_method.customer_id.clone();
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
customer_id: &customer_id,
};
let conn = pg_connection_write(self).await?;
let field = format!("payment_method_id_{}", payment_method.get_id().clone());
let p_update: PaymentMethodUpdateInternal =
payment_method_update.convert_to_payment_method_update(storage_scheme);
let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone());
self.update_resource(
state,
key_store,
storage_scheme,
payment_method
.clone()
.update_with_payment_method_id(&conn, p_update.clone()),
updated_payment_method,
UpdateResourceParams {
updateable: kv::Updateable::PaymentMethodUpdate(Box::new(
kv::PaymentMethodUpdateMems {
orig: payment_method.clone(),
update_data: p_update.clone(),
},
)),
operation: Op::Update(
key.clone(),
&field,
payment_method.clone().updated_by.as_deref(),
),
},
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
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> {
self.router_store
.update_payment_method(
state,
key_store,
payment_method,
payment_method_update,
storage_scheme,
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
self.router_store
.find_payment_method_by_customer_id_merchant_id_list(
state,
key_store,
customer_id,
merchant_id,
limit,
)
.await
}
// Need to fix this once we start moving to v2 for payment method
#[cfg(all(
feature = "v2",
feature = "customer_v2",
feature = "payment_methods_v2"
))]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
self.router_store
.find_payment_method_list_by_global_customer_id(state, key_store, customer_id, limit)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.filter_resources(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
limit,
),
|pm| pm.status == status,
FilterResourceParams {
key: PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
},
pattern: "payment_method_id_*",
limit,
},
)
.await
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[instrument(skip_all)]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
self.router_store
.find_payment_method_by_global_customer_id_merchant_id_status(
state,
key_store,
customer_id,
merchant_id,
status,
limit,
storage_scheme,
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
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> {
self.router_store
.delete_payment_method_by_merchant_id_payment_method_id(
state,
key_store,
merchant_id,
payment_method_id,
)
.await
}
// Soft delete, Check if KV stuff is needed here
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.delete_payment_method(state, key_store, payment_method)
.await
}
// Check if KV stuff is needed here
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.router_store
.find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
type Error = errors::StorageError;
#[instrument(skip_all)]
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_payment_method_id(&conn, payment_method_id),
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
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 conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_id(&conn, payment_method_id),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_locker_id(&conn, locker_id),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let conn = pg_connection_read(self).await?;
PaymentMethod::get_count_by_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
)
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let conn = pg_connection_read(self).await?;
PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status)
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_new = payment_method
.construct_new()
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
self.call_database(state, key_store, payment_method_new.insert(&conn))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
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 = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
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 = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
payment_method.update_with_id(&conn, payment_method_update.into()),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit),
)
.await
}
// Need to fix this once we move to payment method for customer
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[instrument(skip_all)]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_global_customer_id(&conn, id, limit),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
limit,
),
)
.await
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
#[instrument(skip_all)]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_global_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
limit,
),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
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 conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::delete_by_merchant_id_payment_method_id(
&conn,
merchant_id,
payment_method_id,
),
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
let payment_method_update = PaymentMethodUpdate::StatusUpdate {
status: Some(common_enums::PaymentMethodStatus::Inactive),
};
self.call_database(
state,
key_store,
payment_method.update_with_id(&conn, payment_method_update.into()),
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id),
)
.await
}
}
#[async_trait::async_trait]
impl PaymentMethodInterface for MockDb {
type Error = errors::StorageError;
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.find_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.get_id() == payment_method_id,
"cannot find payment method".to_string(),
)
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
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.find_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.get_id() == payment_method_id,
"cannot find payment method".to_string(),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.find_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.locker_id == Some(locker_id.to_string()),
"cannot find payment method".to_string(),
)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let count = payment_methods
.iter()
.filter(|pm| {
pm.customer_id == *customer_id
&& pm.merchant_id == *merchant_id
&& pm.status == status
})
.count();
i64::try_from(count).change_context(errors::StorageError::MockDbError)
}
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let count = payment_methods
.iter()
.filter(|pm| pm.merchant_id == *merchant_id && pm.status == status)
.count();
i64::try_from(count).change_context(errors::StorageError::MockDbError)
}
async fn insert_payment_method(
&self,
_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)
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
_limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.find_resources(
state,
key_store,
payment_methods,
|pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id,
"cannot find payment method".to_string(),
)
.await
}
// Need to fix this once we complete v2 payment method
#[cfg(all(feature = "v2", feature = "customer_v2"))]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
_id: &id_type::GlobalCustomerId,
_limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
todo!()
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
_limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.find_resources(
state,
key_store,
payment_methods,
|pm| {
pm.customer_id == *customer_id
&& pm.merchant_id == *merchant_id
&& pm.status == status
},
"cannot find payment method".to_string(),
)
.await
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
_limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let find_pm_by = |pm: &&PaymentMethod| {
pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status
};
let error_message = "cannot find payment method".to_string();
self.find_resources(state, key_store, payment_methods, find_pm_by, error_message)
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
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()),
}
}
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
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
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
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.find_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()),
"cannot find payment method".to_string(),
)
.await
}
}
| 7,953 | 1,037 |
hyperswitch | crates/storage_impl/src/mandate.rs | .rs | use diesel_models::Mandate;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for Mandate {}
| 29 | 1,038 |
hyperswitch | crates/storage_impl/src/lib.rs | .rs | use std::{fmt::Debug, sync::Arc};
use diesel_models as store;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
};
use masking::StrongSecret;
use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore};
mod address;
pub mod callback_mapper;
pub mod config;
pub mod connection;
pub mod customers;
pub mod database;
pub mod errors;
pub mod kv_router_store;
pub mod lookup;
pub mod mandate;
pub mod metrics;
pub mod mock_db;
pub mod payment_method;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod redis;
pub mod refund;
mod reverse_lookup;
pub mod utils;
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use database::store::PgPool;
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
pub use mock_db::MockDb;
use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply};
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
pub use crate::{database::store::DatabaseStore, errors::StorageError};
#[derive(Debug, Clone)]
pub struct RouterStore<T: DatabaseStore> {
db_store: T,
cache_store: Arc<RedisStore>,
master_encryption_key: StrongSecret<Vec<u8>>,
pub request_id: Option<String>,
}
#[async_trait::async_trait]
impl<T: DatabaseStore> DatabaseStore for RouterStore<T>
where
T::Config: Send,
{
type Config = (
T::Config,
redis_interface::RedisSettings,
StrongSecret<Vec<u8>>,
tokio::sync::oneshot::Sender<()>,
&'static str,
);
async fn new(
config: Self::Config,
tenant_config: &dyn config::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")
}
}
fn get_master_pool(&self) -> &PgPool {
self.db_store.get_master_pool()
}
fn get_replica_pool(&self) -> &PgPool {
self.db_store.get_replica_pool()
}
fn get_accounts_master_pool(&self) -> &PgPool {
self.db_store.get_accounts_master_pool()
}
fn get_accounts_replica_pool(&self) -> &PgPool {
self.db_store.get_accounts_replica_pool()
}
}
impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {
fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
self.cache_store.get_redis_conn()
}
}
impl<T: DatabaseStore> RouterStore<T> {
pub async fn from_config(
db_conf: T::Config,
tenant_config: &dyn config::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,
})
}
pub async fn cache_store(
cache_conf: &redis_interface::RedisSettings,
cache_error_signal: tokio::sync::oneshot::Sender<()>,
) -> error_stack::Result<Arc<RedisStore>, StorageError> {
let cache_store = RedisStore::new(cache_conf)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to create cache store")?;
cache_store.set_error_callback(cache_error_signal);
Ok(Arc::new(cache_store))
}
pub fn master_key(&self) -> &StrongSecret<Vec<u8>> {
&self.master_encryption_key
}
pub async fn call_database<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query: R,
) -> error_stack::Result<D, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<Output = error_stack::Result<M, diesel_models::errors::DatabaseError>>
+ Send,
M: ReverseConversion<D>,
{
execute_query
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
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)
}
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` is not set
pub async fn test_store(
db_conf: T::Config,
tenant_config: &dyn config::TenantConfig,
cache_conf: &redis_interface::RedisSettings,
encryption_key: StrongSecret<Vec<u8>>,
) -> error_stack::Result<Self, StorageError> {
// TODO: create an error enum and return proper error here
let db_store = T::new(db_conf, tenant_config, true).await?;
let cache_store = RedisStore::new(cache_conf)
.await
.change_context(StorageError::InitializationError)
.attach_printable("failed to create redis cache")?;
Ok(Self {
db_store,
cache_store: Arc::new(cache_store),
master_encryption_key: encryption_key,
request_id: None,
})
}
}
// TODO: This should not be used beyond this crate
// Remove the pub modified once StorageScheme usage is completed
pub trait DataModelExt {
type StorageModel;
fn to_storage_model(self) -> Self::StorageModel;
fn from_storage_model(storage_model: Self::StorageModel) -> Self;
}
pub(crate) fn diesel_error_to_data_error(
diesel_error: diesel_models::errors::DatabaseError,
) -> StorageError {
match diesel_error {
diesel_models::errors::DatabaseError::DatabaseConnectionError => {
StorageError::DatabaseConnectionError
}
diesel_models::errors::DatabaseError::NotFound => {
StorageError::ValueNotFound("Value not found".to_string())
}
diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue {
entity: "entity ",
key: None,
},
_ => StorageError::DatabaseError(error_stack::report!(diesel_error)),
}
}
#[async_trait::async_trait]
pub trait UniqueConstraints {
fn unique_constraints(&self) -> Vec<String>;
fn table_name(&self) -> &str;
async fn check_for_constraints(
&self,
redis_conn: &Arc<RedisConnectionPool>,
) -> CustomResult<(), RedisError> {
let constraints = self.unique_constraints();
let sadd_result = redis_conn
.sadd(
&format!("unique_constraint:{}", self.table_name()).into(),
constraints,
)
.await?;
match sadd_result {
SaddReply::KeyNotSet => Err(error_stack::report!(RedisError::SetAddMembersFailed)),
SaddReply::KeySet => Ok(()),
}
}
}
impl UniqueConstraints for diesel_models::Address {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("address_{}", self.address_id)]
}
fn table_name(&self) -> &str {
"Address"
}
}
#[cfg(feature = "v2")]
impl UniqueConstraints for diesel_models::PaymentIntent {
fn unique_constraints(&self) -> Vec<String> {
vec![self.id.get_string_repr().to_owned()]
}
fn table_name(&self) -> &str {
"PaymentIntent"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::PaymentIntent {
#[cfg(feature = "v1")]
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"pi_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr()
)]
}
#[cfg(feature = "v2")]
fn unique_constraints(&self) -> Vec<String> {
vec![format!("pi_{}", self.id.get_string_repr())]
}
fn table_name(&self) -> &str {
"PaymentIntent"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::PaymentAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"pa_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)]
}
fn table_name(&self) -> &str {
"PaymentAttempt"
}
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))]
impl UniqueConstraints for diesel_models::Refund {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"refund_{}_{}",
self.merchant_id.get_string_repr(),
self.refund_id
)]
}
fn table_name(&self) -> &str {
"Refund"
}
}
#[cfg(all(feature = "v2", feature = "refunds_v2"))]
impl UniqueConstraints for diesel_models::Refund {
fn unique_constraints(&self) -> Vec<String> {
vec![self.id.get_string_repr().to_owned()]
}
fn table_name(&self) -> &str {
"Refund"
}
}
impl UniqueConstraints for diesel_models::ReverseLookup {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("reverselookup_{}", self.lookup_id)]
}
fn table_name(&self) -> &str {
"ReverseLookup"
}
}
#[cfg(feature = "payouts")]
impl UniqueConstraints for diesel_models::Payouts {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"po_{}_{}",
self.merchant_id.get_string_repr(),
self.payout_id
)]
}
fn table_name(&self) -> &str {
"Payouts"
}
}
#[cfg(feature = "payouts")]
impl UniqueConstraints for diesel_models::PayoutAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"poa_{}_{}",
self.merchant_id.get_string_repr(),
self.payout_attempt_id
)]
}
fn table_name(&self) -> &str {
"PayoutAttempt"
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("paymentmethod_{}", self.payment_method_id)]
}
fn table_name(&self) -> &str {
"PaymentMethod"
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
vec![self.id.get_string_repr().to_owned()]
}
fn table_name(&self) -> &str {
"PaymentMethod"
}
}
impl UniqueConstraints for diesel_models::Mandate {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"mand_{}_{}",
self.merchant_id.get_string_repr(),
self.mandate_id
)]
}
fn table_name(&self) -> &str {
"Mandate"
}
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl UniqueConstraints for diesel_models::Customer {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"customer_{}_{}",
self.customer_id.get_string_repr(),
self.merchant_id.get_string_repr(),
)]
}
fn table_name(&self) -> &str {
"Customer"
}
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
impl UniqueConstraints for diesel_models::Customer {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("customer_{}", self.id.get_string_repr())]
}
fn table_name(&self) -> &str {
"Customer"
}
}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {}
| 3,253 | 1,039 |
hyperswitch | crates/storage_impl/src/payouts.rs | .rs | pub mod payout_attempt;
#[allow(clippy::module_inception)]
pub mod payouts;
use diesel_models::{payout_attempt::PayoutAttempt, payouts::Payouts};
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for Payouts {}
impl KvStorePartition for PayoutAttempt {}
| 67 | 1,040 |
hyperswitch | crates/storage_impl/src/errors.rs | .rs | pub use common_enums::{ApiClientError, ApplicationError, ApplicationResult};
pub use redis_interface::errors::RedisError;
use crate::store::errors::DatabaseError;
pub type StorageResult<T> = error_stack::Result<T, StorageError>;
#[derive(Debug, thiserror::Error)]
pub enum StorageError {
#[error("Initialization Error")]
InitializationError,
#[error("DatabaseError: {0:?}")]
DatabaseError(error_stack::Report<DatabaseError>),
#[error("ValueNotFound: {0}")]
ValueNotFound(String),
#[error("DuplicateValue: {entity} already exists {key:?}")]
DuplicateValue {
entity: &'static str,
key: Option<String>,
},
#[error("Timed out while trying to connect to the database")]
DatabaseConnectionError,
#[error("KV error")]
KVError,
#[error("Serialization failure")]
SerializationFailed,
#[error("MockDb error")]
MockDbError,
#[error("Kafka error")]
KafkaError,
#[error("Customer with this id is Redacted")]
CustomerRedacted,
#[error("Deserialization failure")]
DeserializationFailed,
#[error("Error while encrypting data")]
EncryptionError,
#[error("Error while decrypting data from database")]
DecryptionError,
#[error("RedisError: {0:?}")]
RedisError(error_stack::Report<RedisError>),
}
impl From<error_stack::Report<RedisError>> for StorageError {
fn from(err: error_stack::Report<RedisError>) -> Self {
match err.current_context() {
RedisError::NotFound => Self::ValueNotFound("redis value not found".to_string()),
RedisError::JsonSerializationFailed => Self::SerializationFailed,
RedisError::JsonDeserializationFailed => Self::DeserializationFailed,
_ => Self::RedisError(err),
}
}
}
impl From<diesel::result::Error> for StorageError {
fn from(err: diesel::result::Error) -> Self {
Self::from(error_stack::report!(DatabaseError::from(err)))
}
}
impl From<error_stack::Report<DatabaseError>> for StorageError {
fn from(err: error_stack::Report<DatabaseError>) -> Self {
match err.current_context() {
DatabaseError::DatabaseConnectionError => Self::DatabaseConnectionError,
DatabaseError::NotFound => Self::ValueNotFound(String::from("db value not found")),
DatabaseError::UniqueViolation => Self::DuplicateValue {
entity: "db entity",
key: None,
},
_ => Self::DatabaseError(err),
}
}
}
impl StorageError {
pub fn is_db_not_found(&self) -> bool {
match self {
Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound),
Self::ValueNotFound(_) => true,
Self::RedisError(err) => matches!(err.current_context(), RedisError::NotFound),
_ => false,
}
}
pub fn is_db_unique_violation(&self) -> bool {
match self {
Self::DatabaseError(err) => {
matches!(err.current_context(), DatabaseError::UniqueViolation,)
}
Self::DuplicateValue { .. } => true,
_ => false,
}
}
}
pub trait RedisErrorExt {
#[track_caller]
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError>;
}
impl RedisErrorExt for error_stack::Report<RedisError> {
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError> {
match self.current_context() {
RedisError::NotFound => self.change_context(StorageError::ValueNotFound(format!(
"Data does not exist for key {key}",
))),
RedisError::SetNxFailed | RedisError::SetAddMembersFailed => {
self.change_context(StorageError::DuplicateValue {
entity: "redis",
key: Some(key.to_string()),
})
}
_ => self.change_context(StorageError::KVError),
}
}
}
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
payment_experience: String,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Failed to parse Wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckDBError {
#[error("Error while connecting to database")]
DBError,
#[error("Error while writing to database")]
DBWriteError,
#[error("Error while reading element in the database")]
DBReadError,
#[error("Error while deleting element in the database")]
DBDeleteError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error in database transaction")]
TransactionError,
#[error("Error while executing query in Sqlx Analytics")]
SqlxAnalyticsError,
#[error("Error while executing query in Clickhouse Analytics")]
ClickhouseAnalyticsError,
#[error("Error while executing query in Opensearch")]
OpensearchError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DBError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckRedisError {
#[error("Failed to establish Redis connection")]
RedisConnectionError,
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckLockerError {
#[error("Failed to establish Locker connection")]
FailedToCallLocker,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckGRPCServiceError {
#[error("Failed to establish connection with gRPC service")]
FailedToCallService,
}
#[derive(thiserror::Error, Debug, Clone)]
pub enum RecoveryError {
#[error("Failed to make a recovery payment")]
PaymentCallFailed,
#[error("Encountered a Process Tracker Task Failure")]
ProcessTrackerFailure,
#[error("The encountered task is invalid")]
InvalidTask,
#[error("The Intended data was not found")]
ValueNotFound,
#[error("Failed to update billing connector")]
RecordBackToBillingConnectorFailed,
#[error("Failed to fetch billing connector account id")]
BillingMerchantConnectorAccountIdNotFound,
}
| 2,250 | 1,041 |
hyperswitch | crates/storage_impl/src/redis.rs | .rs | pub mod cache;
pub mod kv_store;
pub mod pub_sub;
use std::sync::{atomic, Arc};
use router_env::tracing::Instrument;
use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface};
#[derive(Clone)]
pub struct RedisStore {
// Maybe expose the redis_conn via traits instead of the making the field public
pub(crate) redis_conn: Arc<redis_interface::RedisConnectionPool>,
}
impl std::fmt::Debug for RedisStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CacheStore")
.field("redis_conn", &"Redis conn doesn't implement debug")
.finish()
}
}
impl RedisStore {
pub async fn new(
conf: &redis_interface::RedisSettings,
) -> error_stack::Result<Self, redis_interface::errors::RedisError> {
Ok(Self {
redis_conn: Arc::new(redis_interface::RedisConnectionPool::new(conf).await?),
})
}
pub fn set_error_callback(&self, callback: tokio::sync::oneshot::Sender<()>) {
let redis_clone = self.redis_conn.clone();
let _task_handle = tokio::spawn(
async move {
redis_clone.on_error(callback).await;
}
.in_current_span(),
);
}
}
impl RedisConnInterface for RedisStore {
fn get_redis_conn(
&self,
) -> error_stack::Result<
Arc<redis_interface::RedisConnectionPool>,
redis_interface::errors::RedisError,
> {
if self
.redis_conn
.is_redis_available
.load(atomic::Ordering::SeqCst)
{
Ok(self.redis_conn.clone())
} else {
Err(redis_interface::errors::RedisError::RedisConnectionError.into())
}
}
}
| 404 | 1,042 |
hyperswitch | crates/storage_impl/src/reverse_lookup.rs | .rs | use diesel_models::reverse_lookup::ReverseLookup;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for ReverseLookup {}
| 31 | 1,043 |
hyperswitch | crates/storage_impl/src/mock_db/payment_intent.rs | .rs | use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
behaviour::Conversion,
merchant_key_store::MerchantKeyStore,
payments::{
payment_intent::{PaymentIntentInterface, PaymentIntentUpdate},
PaymentIntent,
},
};
use super::MockDb;
use crate::errors::StorageError;
#[async_trait::async_trait]
impl PaymentIntentInterface for MockDb {
type Error = StorageError;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intent_by_constraints(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
)>,
StorageError,
> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_time_range: &common_utils::types::TimeRange,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
)>,
StorageError,
> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[allow(clippy::panic)]
async fn insert_payment_intent(
&self,
_state: &KeyManagerState,
new: PaymentIntent,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
payment_intents.push(new.clone());
Ok(new)
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
update: PaymentIntentUpdate,
key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter_mut()
.find(|item| item.get_id() == this.get_id() && item.merchant_id == this.merchant_id)
.unwrap();
let diesel_payment_intent_update = diesel_models::PaymentIntentUpdate::from(update);
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
*payment_intent = PaymentIntent::convert_back(
state,
diesel_payment_intent_update.apply_changeset(diesel_payment_intent),
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(payment_intent.clone())
}
#[cfg(feature = "v2")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
update: PaymentIntentUpdate,
key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
todo!()
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
_state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
Ok(payment_intents
.iter()
.find(|payment_intent| {
payment_intent.get_id() == payment_id && payment_intent.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_id(
&self,
_state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter()
.find(|payment_intent| payment_intent.get_id() == id)
.ok_or(StorageError::ValueNotFound(
"PaymentIntent not found".to_string(),
))?;
Ok(payment_intent.clone())
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
_state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: &common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter()
.find(|payment_intent| {
payment_intent.merchant_reference_id.as_ref() == Some(merchant_reference_id)
&& payment_intent.profile_id.eq(profile_id)
})
.ok_or(StorageError::ValueNotFound(
"PaymentIntent not found".to_string(),
))?;
Ok(payment_intent.clone())
}
}
| 2,077 | 1,044 |
hyperswitch | crates/storage_impl/src/mock_db/redis_conn.rs | .rs | use std::sync::Arc;
use redis_interface::errors::RedisError;
use super::MockDb;
use crate::redis::kv_store::RedisConnInterface;
impl RedisConnInterface for MockDb {
fn get_redis_conn(
&self,
) -> Result<Arc<redis_interface::RedisConnectionPool>, error_stack::Report<RedisError>> {
self.redis.get_redis_conn()
}
}
| 85 | 1,045 |
hyperswitch | crates/storage_impl/src/mock_db/payout_attempt.rs | .rs | use common_utils::errors::CustomResult;
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::payouts::{
payout_attempt::{
PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,
},
payouts::Payouts,
};
use super::MockDb;
use crate::errors::StorageError;
#[async_trait::async_trait]
impl PayoutAttemptInterface for MockDb {
type Error = StorageError;
async fn update_payout_attempt(
&self,
_this: &PayoutAttempt,
_payout_attempt_update: PayoutAttemptUpdate,
_payouts: &Payouts,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PayoutAttempt, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn insert_payout_attempt(
&self,
_payout_attempt: PayoutAttemptNew,
_payouts: &Payouts,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PayoutAttempt, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payout_attempt_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PayoutAttempt, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_payout_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PayoutAttempt, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn get_filters_for_payouts(
&self,
_payouts: &[Payouts],
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters,
StorageError,
> {
Err(StorageError::MockDbError)?
}
}
| 562 | 1,046 |
hyperswitch | crates/storage_impl/src/mock_db/payouts.rs | .rs | use common_utils::errors::CustomResult;
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttempt,
payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},
};
use crate::{errors::StorageError, MockDb};
#[async_trait::async_trait]
impl PayoutsInterface for MockDb {
type Error = StorageError;
async fn find_payout_by_merchant_id_payout_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payout_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Payouts, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn update_payout(
&self,
_this: &Payouts,
_payout_update: PayoutsUpdate,
_payout_attempt: &PayoutAttempt,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Payouts, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn insert_payout(
&self,
_payout: PayoutsNew,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Payouts, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payout_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<Payouts>, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn filter_payouts_by_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn filter_payouts_and_attempts(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<
Vec<(
Payouts,
PayoutAttempt,
Option<diesel_models::Customer>,
Option<diesel_models::Address>,
)>,
StorageError,
> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_time_range: &common_utils::types::TimeRange,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn get_total_count_of_filtered_payouts(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_active_payout_ids: &[String],
_connector: Option<Vec<api_models::enums::PayoutConnectors>>,
_currency: Option<Vec<storage_enums::Currency>>,
_status: Option<Vec<storage_enums::PayoutStatus>>,
_payout_method: Option<Vec<storage_enums::PayoutType>>,
) -> CustomResult<i64, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn filter_active_payout_ids_by_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
) -> CustomResult<Vec<String>, StorageError> {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
}
| 1,034 | 1,047 |
hyperswitch | crates/storage_impl/src/mock_db/payment_attempt.rs | .rs | use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]
use common_utils::{id_type, types::keymanager::KeyManagerState};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
use hyperswitch_domain_models::payments::payment_attempt::{
PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate,
};
use super::MockDb;
use crate::errors::StorageError;
#[cfg(feature = "v1")]
use crate::DataModelExt;
#[async_trait::async_trait]
impl PaymentAttemptInterface for MockDb {
type Error = StorageError;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
_payment_id: &common_utils::id_type::PaymentId,
_merchant_id: &common_utils::id_type::MerchantId,
_attempt_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filters_for_payments(
&self,
_pi: &[hyperswitch_domain_models::payments::PaymentIntent],
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
StorageError,
> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_total_count_of_filtered_payment_attempts(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_active_attempt_ids: &[String],
_connector: Option<Vec<api_models::enums::Connector>>,
_payment_method: Option<Vec<common_enums::PaymentMethod>>,
_payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
_authentication_type: Option<Vec<common_enums::AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
_card_network: Option<Vec<storage_enums::CardNetwork>>,
_card_discovery: Option<Vec<storage_enums::CardDiscovery>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_total_count_of_filtered_payment_attempts(
&self,
_merchant_id: &id_type::MerchantId,
_active_attempt_ids: &[String],
_connector: Option<api_models::enums::Connector>,
_payment_method_type: Option<common_enums::PaymentMethod>,
_payment_method_subtype: Option<common_enums::PaymentMethodType>,
_authentication_type: Option<common_enums::AuthenticationType>,
_merchanat_connector_id: Option<id_type::MerchantConnectorAccountId>,
_card_network: Option<storage_enums::CardNetwork>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
_attempt_id: &str,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_id(
&self,
_key_manager_state: &KeyManagerState,
_merchant_key_store: &MerchantKeyStore,
_attempt_id: &id_type::GlobalAttemptId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
async fn find_payment_attempts_by_payment_intent_id(
&self,
_key_manager_state: &KeyManagerState,
_id: &id_type::GlobalPaymentId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
_preprocessing_id: &str,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_txn_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_profile_id_connector_transaction_id(
&self,
_key_manager_state: &KeyManagerState,
_merchant_key_store: &MerchantKeyStore,
_profile_id: &id_type::ProfileId,
_connector_transaction_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_attempts_by_merchant_id_payment_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payment_id: &common_utils::id_type::PaymentId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
#[allow(clippy::panic)]
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
let time = common_utils::date_time::now();
let payment_attempt = PaymentAttempt {
payment_id: payment_attempt.payment_id,
merchant_id: payment_attempt.merchant_id,
attempt_id: payment_attempt.attempt_id,
status: payment_attempt.status,
net_amount: payment_attempt.net_amount,
currency: payment_attempt.currency,
save_to_locker: payment_attempt.save_to_locker,
connector: payment_attempt.connector,
error_message: payment_attempt.error_message,
offer_amount: payment_attempt.offer_amount,
payment_method_id: payment_attempt.payment_method_id,
payment_method: payment_attempt.payment_method,
connector_transaction_id: None,
capture_method: payment_attempt.capture_method,
capture_on: payment_attempt.capture_on,
confirm: payment_attempt.confirm,
authentication_type: payment_attempt.authentication_type,
created_at: payment_attempt.created_at.unwrap_or(time),
modified_at: payment_attempt.modified_at.unwrap_or(time),
last_synced: payment_attempt.last_synced,
cancellation_reason: payment_attempt.cancellation_reason,
amount_to_capture: payment_attempt.amount_to_capture,
mandate_id: None,
browser_info: None,
payment_token: None,
error_code: payment_attempt.error_code,
connector_metadata: None,
charge_id: None,
payment_experience: payment_attempt.payment_experience,
payment_method_type: payment_attempt.payment_method_type,
payment_method_data: payment_attempt.payment_method_data,
business_sub_label: payment_attempt.business_sub_label,
straight_through_algorithm: payment_attempt.straight_through_algorithm,
mandate_details: payment_attempt.mandate_details,
preprocessing_step_id: payment_attempt.preprocessing_step_id,
error_reason: payment_attempt.error_reason,
multiple_capture_count: payment_attempt.multiple_capture_count,
connector_response_reference_id: None,
amount_capturable: payment_attempt.amount_capturable,
updated_by: storage_scheme.to_string(),
authentication_data: payment_attempt.authentication_data,
encoded_data: payment_attempt.encoded_data,
merchant_connector_id: payment_attempt.merchant_connector_id,
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
external_three_ds_authentication_attempted: payment_attempt
.external_three_ds_authentication_attempted,
authentication_connector: payment_attempt.authentication_connector,
authentication_id: payment_attempt.authentication_id,
mandate_data: payment_attempt.mandate_data,
payment_method_billing_address_id: payment_attempt.payment_method_billing_address_id,
fingerprint_id: payment_attempt.fingerprint_id,
client_source: payment_attempt.client_source,
client_version: payment_attempt.client_version,
customer_acceptance: payment_attempt.customer_acceptance,
organization_id: payment_attempt.organization_id,
profile_id: payment_attempt.profile_id,
connector_mandate_detail: payment_attempt.connector_mandate_detail,
request_extended_authorization: payment_attempt.request_extended_authorization,
extended_authorization_applied: payment_attempt.extended_authorization_applied,
capture_before: payment_attempt.capture_before,
card_discovery: payment_attempt.card_discovery,
charges: None,
issuer_error_code: None,
issuer_error_message: None,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
}
#[cfg(feature = "v2")]
#[allow(clippy::panic)]
async fn insert_payment_attempt(
&self,
_key_manager_state: &KeyManagerState,
_merchant_key_store: &MerchantKeyStore,
_payment_attempt: PaymentAttempt,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_attempt_with_attempt_id(
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
let item = payment_attempts
.iter_mut()
.find(|item| item.attempt_id == this.attempt_id)
.unwrap();
*item = PaymentAttempt::from_storage_model(
payment_attempt
.to_storage_model()
.apply_changeset(this.to_storage_model()),
);
Ok(item.clone())
}
#[cfg(feature = "v2")]
async fn update_payment_attempt(
&self,
_key_manager_state: &KeyManagerState,
_merchant_key_store: &MerchantKeyStore,
_this: PaymentAttempt,
_payment_attempt: PaymentAttemptUpdate,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&self,
_connector_transaction_id: &common_utils::types::ConnectorTransactionId,
_payment_id: &common_utils::id_type::PaymentId,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
Ok(payment_attempts
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == *payment_id
&& payment_attempt.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
}
#[cfg(feature = "v1")]
#[allow(clippy::unwrap_used)]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
Ok(payment_attempts
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == *payment_id
&& payment_attempt.merchant_id.eq(merchant_id)
&& (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged
|| payment_attempt.status == storage_enums::AttemptStatus::Charged)
})
.cloned()
.unwrap())
}
}
| 3,154 | 1,048 |
hyperswitch | crates/storage_impl/src/payments/payment_intent.rs | .rs | #[cfg(feature = "olap")]
use api_models::payments::{AmountFilter, Order, SortBy, SortOn};
#[cfg(feature = "olap")]
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::{
ext_traits::{AsyncExt, Encode},
types::keymanager::KeyManagerState,
};
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};
#[cfg(feature = "v1")]
use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate;
#[cfg(feature = "olap")]
use diesel_models::query::generics::db_metrics;
#[cfg(all(feature = "v1", feature = "olap"))]
use diesel_models::schema::{
payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl},
payment_intent::dsl as pi_dsl,
};
#[cfg(all(feature = "v2", feature = "olap"))]
use diesel_models::schema_v2::{
payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl},
payment_intent::dsl as pi_dsl,
};
use diesel_models::{
enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent,
};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
};
use hyperswitch_domain_models::{
behaviour::Conversion,
merchant_key_store::MerchantKeyStore,
payments::{
payment_intent::{PaymentIntentInterface, PaymentIntentUpdate},
PaymentIntent,
},
};
use redis_interface::HsetnxReply;
#[cfg(feature = "olap")]
use router_env::logger;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use crate::connection;
use crate::{
diesel_error_to_data_error,
errors::{RedisErrorExt, StorageError},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, pg_connection_read, pg_connection_write},
DatabaseStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
type Error = StorageError;
#[cfg(feature = "v1")]
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
payment_intent: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let merchant_id = payment_intent.merchant_id.clone();
let payment_id = payment_intent.get_id().to_owned();
let field = payment_intent.get_id().get_hash_key_for_kv_store();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payment_intent(
state,
payment_intent,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let new_payment_intent = payment_intent
.clone()
.construct_new()
.await
.change_context(StorageError::EncryptionError)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PaymentIntent(Box::new(
new_payment_intent,
))),
},
};
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HSetNx(
&field,
&diesel_payment_intent,
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue {
entity: "payment_intent",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(payment_intent),
Err(error) => Err(error.change_context(StorageError::KVError)),
}
}
}
}
#[cfg(feature = "v2")]
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
payment_intent: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payment_intent(
state,
payment_intent,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
todo!("Implement payment intent insert for kv")
}
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> {
self.router_store
.get_filtered_payment_intents_attempt(
state,
merchant_id,
constraints,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent_update: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let merchant_id = this.merchant_id.clone();
let payment_id = this.get_id().to_owned();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let field = format!("pi_{}", this.get_id().get_string_repr());
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payment_intent(
state,
this,
payment_intent_update,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update);
let origin_diesel_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?;
let diesel_intent = diesel_intent_update
.clone()
.apply_changeset(origin_diesel_intent.clone());
// Check for database presence as well Maybe use a read replica here ?
let redis_value = diesel_intent
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new(
kv::PaymentIntentUpdateMems {
orig: origin_diesel_intent,
update_data: diesel_intent_update,
},
))),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(StorageError::KVError)?;
let payment_intent = PaymentIntent::convert_back(
state,
diesel_intent,
merchant_key_store.key.get_inner(),
merchant_id.into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(payment_intent)
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent_update: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payment_intent(
state,
this,
payment_intent_update,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
todo!()
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Find,
))
.await;
let diesel_payment_intent = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
let field = payment_id.get_hash_key_for_kv_store();
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_intent_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn: bb8::PooledConnection<
'_,
async_bb8_diesel::ConnectionManager<diesel::PgConnection>,
> = pg_connection_read(self).await?;
let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
self.router_store
.filter_payment_intent_by_constraints(
state,
merchant_id,
filters,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
self.router_store
.filter_payment_intents_by_time_range_constraints(
state,
merchant_id,
time_range,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
self.router_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
self.router_store
.get_filtered_payment_intents_attempt(
state,
merchant_id,
filters,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
self.router_store
.get_filtered_active_attempt_ids_for_total_count(
merchant_id,
constraints,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
self.router_store
.get_filtered_active_attempt_ids_for_total_count(
merchant_id,
constraints,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: &MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_intent_by_merchant_reference_id_profile_id(
state,
merchant_reference_id,
profile_id,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
todo!()
}
}
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
payment_intent: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_write(self).await?;
let diesel_payment_intent = payment_intent
.construct_new()
.await
.change_context(StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_write(self).await?;
let diesel_payment_intent_update = DieselPaymentIntentUpdate::from(payment_intent);
let diesel_payment_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?
.update(&conn, diesel_payment_intent_update)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_write(self).await?;
let diesel_payment_intent_update =
diesel_models::PaymentIntentUpdateInternal::try_from(payment_intent)
.change_context(StorageError::DeserializationFailed)?;
let diesel_payment_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?
.update(&conn, diesel_payment_intent_update)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.async_and_then(|diesel_payment_intent| async {
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_intent_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_read(self).await?;
let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: &MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_read(self).await?;
let diesel_payment_intent = DieselPaymentIntent::find_by_merchant_reference_id_profile_id(
&conn,
merchant_reference_id,
profile_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
use futures::{future::try_join_all, FutureExt};
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
let mut query = <DieselPaymentIntent as HasTable>::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(pi_dsl::created_at.desc())
.into_boxed();
match filters {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));
}
PaymentIntentFetchConstraints::List(params) => {
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
starting_after_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
ending_before_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
if let Some(currency) = ¶ms.currency {
query = query.filter(pi_dsl::currency.eq_any(currency.clone()));
}
if let Some(status) = ¶ms.status {
query = query.filter(pi_dsl::status.eq_any(status.clone()));
}
}
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<DieselPaymentIntent>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map(|payment_intents| {
try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| {
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
})?
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
// TODO: Remove this redundant function
let payment_filters = (*time_range).into();
self.filter_payment_intent_by_constraints(
state,
merchant_id,
&payment_filters,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn get_intent_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = <DieselPaymentIntent as HasTable>::table()
.group_by(pi_dsl::status)
.select((pi_dsl::status, diesel::dsl::count_star()))
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id));
}
query = query.filter(pi_dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<(common_enums::IntentStatus, i64)>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
.into()
})
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
use futures::{future::try_join_all, FutureExt};
use crate::DataModelExt;
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.inner_join(
payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
)
.filter(pa_dsl::merchant_id.eq(merchant_id.to_owned())) // Ensure merchant_ids match, as different merchants can share payment/attempt IDs.
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))
}
PaymentIntentFetchConstraints::List(params) => {
query = match params.order {
Order {
on: SortOn::Amount,
by: SortBy::Asc,
} => query.order(pi_dsl::amount.asc()),
Order {
on: SortOn::Amount,
by: SortBy::Desc,
} => query.order(pi_dsl::amount.desc()),
Order {
on: SortOn::Created,
by: SortBy::Asc,
} => query.order(pi_dsl::created_at.asc()),
Order {
on: SortOn::Created,
by: SortBy::Desc,
} => query.order(pi_dsl::created_at.desc()),
};
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
starting_after_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
ending_before_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
let connectors = params
.connector
.as_ref()
.map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>());
query = match connectors {
Some(connectors) => query.filter(pa_dsl::connector.eq_any(connectors)),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
query = match ¶ms.payment_method {
Some(payment_method) => {
query.filter(pa_dsl::payment_method.eq_any(payment_method.clone()))
}
None => query,
};
query = match ¶ms.payment_method_type {
Some(payment_method_type) => query
.filter(pa_dsl::payment_method_type.eq_any(payment_method_type.clone())),
None => query,
};
query = match ¶ms.authentication_type {
Some(authentication_type) => query
.filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())),
None => query,
};
query = match ¶ms.merchant_connector_id {
Some(merchant_connector_id) => query.filter(
pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()),
),
None => query,
};
if let Some(card_network) = ¶ms.card_network {
query = query.filter(pa_dsl::card_network.eq_any(card_network.clone()));
}
if let Some(card_discovery) = ¶ms.card_discovery {
query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone()));
}
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async::<(
DieselPaymentIntent,
diesel_models::payment_attempt::PaymentAttempt,
)>(conn)
.await
.map(|results| {
try_join_all(results.into_iter().map(|(pi, pa)| {
PaymentIntent::convert_back(
state,
pi,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.map(|payment_intent| {
payment_intent.map(|payment_intent| {
(payment_intent, PaymentAttempt::from_storage_model(pa))
})
})
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
})?
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> {
use diesel::NullableExpressionMethods as _;
use futures::{future::try_join_all, FutureExt};
use crate::DataModelExt;
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.left_join(
payment_attempt_schema::table
.on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())),
)
// Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query.filter(pi_dsl::id.eq(payment_intent_id.to_owned()))
}
PaymentIntentFetchConstraints::List(params) => {
query = match params.order {
Order {
on: SortOn::Amount,
by: SortBy::Asc,
} => query.order(pi_dsl::amount.asc()),
Order {
on: SortOn::Amount,
by: SortBy::Desc,
} => query.order(pi_dsl::amount.desc()),
Order {
on: SortOn::Created,
by: SortBy::Asc,
} => query.order(pi_dsl::created_at.asc()),
Order {
on: SortOn::Created,
by: SortBy::Desc,
} => query.order(pi_dsl::created_at.desc()),
};
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payment_intent_by_id(
state,
starting_after_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payment_intent_by_id(
state,
ending_before_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq(*currency)),
None => query,
};
query = match ¶ms.connector {
Some(connector) => query.filter(pa_dsl::connector.eq(*connector)),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq(*status)),
None => query,
};
query = match ¶ms.payment_method_type {
Some(payment_method_type) => {
query.filter(pa_dsl::payment_method_type_v2.eq(*payment_method_type))
}
None => query,
};
query = match ¶ms.payment_method_subtype {
Some(payment_method_subtype) => {
query.filter(pa_dsl::payment_method_subtype.eq(*payment_method_subtype))
}
None => query,
};
query = match ¶ms.authentication_type {
Some(authentication_type) => {
query.filter(pa_dsl::authentication_type.eq(*authentication_type))
}
None => query,
};
query = match ¶ms.merchant_connector_id {
Some(merchant_connector_id) => query
.filter(pa_dsl::merchant_connector_id.eq(merchant_connector_id.clone())),
None => query,
};
if let Some(card_network) = ¶ms.card_network {
query = query.filter(pa_dsl::card_network.eq(card_network.clone()));
}
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async::<(
DieselPaymentIntent,
Option<diesel_models::payment_attempt::PaymentAttempt>,
)>(conn)
.await
.change_context(StorageError::DecryptionError)
.async_and_then(|output| async {
try_join_all(output.into_iter().map(
|(pi, pa): (_, Option<diesel_models::payment_attempt::PaymentAttempt>)| async {
let payment_intent = PaymentIntent::convert_back(
state,
pi,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
);
let payment_attempt = pa
.async_map(|val| {
PaymentAttempt::convert_back(
state,
val,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
})
.map(|val| val.transpose());
let output = futures::try_join!(payment_intent, payment_attempt);
output.change_context(StorageError::DecryptionError)
},
))
.await
})
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.select(pi_dsl::active_attempt_id)
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(pi_dsl::created_at.desc())
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query.filter(pi_dsl::id.eq(payment_intent_id.to_owned()))
}
PaymentIntentFetchConstraints::List(params) => {
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
}
query = match params.starting_at {
Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)),
None => query,
};
query = match params.ending_at {
Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
None => query,
};
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq(*currency)),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq(*status)),
None => query,
};
query
}
};
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<Option<String>>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
.into()
})
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.select(pi_dsl::active_attempt_id)
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(pi_dsl::created_at.desc())
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))
}
PaymentIntentFetchConstraints::List(params) => {
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match params.starting_at {
Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)),
None => query,
};
query = match params.ending_at {
Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
None => query,
};
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
query
}
};
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<String>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
.into()
})
}
}
| 11,201 | 1,049 |
hyperswitch | crates/storage_impl/src/payments/payment_attempt.rs | .rs | #[cfg(feature = "v2")]
use common_utils::types::keymanager::KeyManagerState;
use common_utils::{
errors::CustomResult,
fallback_reverse_lookup_not_found,
types::{ConnectorTransactionId, ConnectorTransactionIdTrait},
};
use diesel_models::{
enums::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
MandateDetails as DieselMandateDetails, MerchantStorageScheme,
},
kv,
payment_attempt::{
PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew,
},
reverse_lookup::{ReverseLookup, ReverseLookupNew},
};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
};
use hyperswitch_domain_models::{
mandates::{MandateAmountData, MandateDataType, MandateDetails},
payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate},
};
#[cfg(feature = "olap")]
use hyperswitch_domain_models::{
payments::payment_attempt::PaymentListFilters, payments::PaymentIntent,
};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use crate::{
diesel_error_to_data_error,
errors::{self, RedisErrorExt},
kv_router_store::KVRouterStore,
lookup::ReverseLookupInterface,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get},
DataModelExt, DatabaseStore, RouterStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
payment_attempt
.to_storage_model()
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn insert_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
payment_attempt: PaymentAttempt,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
payment_attempt
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| {
let new_error = diesel_error_to_data_error(*error.current_context());
error.change_context(new_error)
})?
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_attempt_with_attempt_id(
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
this.to_storage_model()
.update_with_attempt_id(&conn, payment_attempt.to_storage_model())
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
Conversion::convert(this)
.await
.change_context(errors::StorageError::EncryptionError)?
.update_with_attempt_id(
&conn,
diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt),
)
.await
.map_err(|error| {
let new_error = diesel_error_to_data_error(*error.current_context());
error.change_context(new_error)
})?
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&self,
connector_transaction_id: &ConnectorTransactionId,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id(
&conn,
connector_transaction_id,
payment_id,
merchant_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id(
&conn,
payment_id,
merchant_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&conn,
payment_id,
merchant_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_merchant_id_connector_txn_id(
&conn,
merchant_id,
connector_txn_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_profile_id_connector_transaction_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
connector_txn_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_profile_id_connector_transaction_id(
&conn,
profile_id,
connector_txn_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_payment_id_merchant_id_attempt_id(
&conn,
payment_id,
merchant_id,
attempt_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filters_for_payments(
&self,
pi: &[PaymentIntent],
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentListFilters, errors::StorageError> {
use hyperswitch_domain_models::behaviour::Conversion;
let conn = pg_connection_read(self).await?;
let intents = futures::future::try_join_all(pi.iter().cloned().map(|pi| async {
Conversion::convert(pi)
.await
.change_context(errors::StorageError::EncryptionError)
}))
.await?;
DieselPaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(
|(
connector,
currency,
status,
payment_method,
payment_method_type,
authentication_type,
)| PaymentListFilters {
connector,
currency,
status,
payment_method,
payment_method_type,
authentication_type,
},
)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_merchant_id_preprocessing_id(
&conn,
merchant_id,
preprocessing_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_attempts_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(|a| {
a.into_iter()
.map(PaymentAttempt::from_storage_model)
.collect()
})
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
attempt_id: &common_utils::id_type::GlobalAttemptId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_id(&conn, attempt_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_attempts_by_payment_intent_id(
&self,
key_manager_state: &KeyManagerState,
payment_id: &common_utils::id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
use common_utils::ext_traits::AsyncExt;
let conn = pg_connection_read(self).await?;
DieselPaymentAttempt::find_by_payment_id(&conn, payment_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.async_and_then(|payment_attempts| async {
let mut domain_payment_attempts = Vec::with_capacity(payment_attempts.len());
for attempt in payment_attempts.into_iter() {
domain_payment_attempts.push(
attempt
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
);
}
Ok(domain_payment_attempts)
})
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<api_models::enums::Connector>>,
payment_method: Option<Vec<common_enums::PaymentMethod>>,
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<common_enums::CardNetwork>>,
card_discovery: Option<Vec<common_enums::CardDiscovery>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = self
.db_store
.get_replica_pool()
.get()
.await
.change_context(errors::StorageError::DatabaseConnectionError)?;
let connector_strings = connector.as_ref().map(|connector| {
connector
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
});
DieselPaymentAttempt::get_total_count_of_attempts(
&conn,
merchant_id,
active_attempt_ids,
connector_strings,
payment_method,
payment_method_type,
authentication_type,
merchant_connector_id,
card_network,
card_discovery,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<api_models::enums::Connector>,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
card_network: Option<common_enums::CardNetwork>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = self
.db_store
.get_replica_pool()
.get()
.await
.change_context(errors::StorageError::DatabaseConnectionError)?;
DieselPaymentAttempt::get_total_count_of_attempts(
&conn,
merchant_id,
active_attempt_ids,
connector.map(|val| val.to_string()),
payment_method_type,
payment_method_subtype,
authentication_type,
merchant_connector_id,
card_network,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payment_attempt(payment_attempt, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let merchant_id = payment_attempt.merchant_id.clone();
let payment_id = payment_attempt.payment_id.clone();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let key_str = key.to_string();
let created_attempt = PaymentAttempt {
payment_id: payment_attempt.payment_id.clone(),
merchant_id: payment_attempt.merchant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
net_amount: payment_attempt.net_amount.clone(),
currency: payment_attempt.currency,
save_to_locker: payment_attempt.save_to_locker,
connector: payment_attempt.connector.clone(),
error_message: payment_attempt.error_message.clone(),
offer_amount: payment_attempt.offer_amount,
payment_method_id: payment_attempt.payment_method_id.clone(),
payment_method: payment_attempt.payment_method,
connector_transaction_id: None,
capture_method: payment_attempt.capture_method,
capture_on: payment_attempt.capture_on,
confirm: payment_attempt.confirm,
authentication_type: payment_attempt.authentication_type,
created_at: payment_attempt
.created_at
.unwrap_or_else(common_utils::date_time::now),
modified_at: payment_attempt
.created_at
.unwrap_or_else(common_utils::date_time::now),
last_synced: payment_attempt.last_synced,
amount_to_capture: payment_attempt.amount_to_capture,
cancellation_reason: payment_attempt.cancellation_reason.clone(),
mandate_id: payment_attempt.mandate_id.clone(),
browser_info: payment_attempt.browser_info.clone(),
payment_token: payment_attempt.payment_token.clone(),
error_code: payment_attempt.error_code.clone(),
connector_metadata: payment_attempt.connector_metadata.clone(),
payment_experience: payment_attempt.payment_experience,
payment_method_type: payment_attempt.payment_method_type,
payment_method_data: payment_attempt.payment_method_data.clone(),
business_sub_label: payment_attempt.business_sub_label.clone(),
straight_through_algorithm: payment_attempt.straight_through_algorithm.clone(),
mandate_details: payment_attempt.mandate_details.clone(),
preprocessing_step_id: payment_attempt.preprocessing_step_id.clone(),
error_reason: payment_attempt.error_reason.clone(),
multiple_capture_count: payment_attempt.multiple_capture_count,
connector_response_reference_id: None,
charge_id: None,
amount_capturable: payment_attempt.amount_capturable,
updated_by: storage_scheme.to_string(),
authentication_data: payment_attempt.authentication_data.clone(),
encoded_data: payment_attempt.encoded_data.clone(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
unified_code: payment_attempt.unified_code.clone(),
unified_message: payment_attempt.unified_message.clone(),
external_three_ds_authentication_attempted: payment_attempt
.external_three_ds_authentication_attempted,
authentication_connector: payment_attempt.authentication_connector.clone(),
authentication_id: payment_attempt.authentication_id.clone(),
mandate_data: payment_attempt.mandate_data.clone(),
payment_method_billing_address_id: payment_attempt
.payment_method_billing_address_id
.clone(),
fingerprint_id: payment_attempt.fingerprint_id.clone(),
client_source: payment_attempt.client_source.clone(),
client_version: payment_attempt.client_version.clone(),
customer_acceptance: payment_attempt.customer_acceptance.clone(),
organization_id: payment_attempt.organization_id.clone(),
profile_id: payment_attempt.profile_id.clone(),
connector_mandate_detail: payment_attempt.connector_mandate_detail.clone(),
request_extended_authorization: payment_attempt.request_extended_authorization,
extended_authorization_applied: payment_attempt.extended_authorization_applied,
capture_before: payment_attempt.capture_before,
card_discovery: payment_attempt.card_discovery,
charges: None,
issuer_error_code: None,
issuer_error_message: None,
};
let field = format!("pa_{}", created_attempt.attempt_id);
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new(
payment_attempt.to_storage_model(),
))),
},
};
//Reverse lookup for attempt_id
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
"pa_{}_{}",
created_attempt.merchant_id.get_string_repr(),
&created_attempt.attempt_id,
),
pk_id: key_str.clone(),
sk_id: field.clone(),
source: "payment_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
match Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
self,
KvOperation::HSetNx(
&field,
&created_attempt.clone().to_storage_model(),
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "payment attempt",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_attempt),
Err(error) => Err(error.change_context(errors::StorageError::KVError)),
}
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn insert_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
payment_attempt: PaymentAttempt,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
// Ignoring storage scheme for v2 implementation
self.router_store
.insert_payment_attempt(
key_manager_state,
merchant_key_store,
payment_attempt,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_attempt_with_attempt_id(
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &this.merchant_id,
payment_id: &this.payment_id,
};
let field = format!("pa_{}", this.attempt_id);
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payment_attempt_with_attempt_id(this, payment_attempt, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let old_connector_transaction_id = &this.get_connector_payment_id();
let old_preprocessing_id = &this.preprocessing_step_id;
let updated_attempt = PaymentAttempt::from_storage_model(
payment_attempt
.clone()
.to_storage_model()
.apply_changeset(this.clone().to_storage_model()),
);
// Check for database presence as well Maybe use a read replica here ?
let redis_value = serde_json::to_string(&updated_attempt)
.change_context(errors::StorageError::KVError)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new(
kv::PaymentAttemptUpdateMems {
orig: this.clone().to_storage_model(),
update_data: payment_attempt.to_storage_model(),
},
))),
},
};
match (
old_connector_transaction_id,
&updated_attempt.get_connector_payment_id(),
) {
(None, Some(connector_transaction_id)) => {
add_connector_txn_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.attempt_id.as_str(),
connector_transaction_id,
storage_scheme,
)
.await?;
}
(Some(old_connector_transaction_id), Some(connector_transaction_id)) => {
if old_connector_transaction_id.ne(connector_transaction_id) {
add_connector_txn_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.attempt_id.as_str(),
connector_transaction_id,
storage_scheme,
)
.await?;
}
}
(_, _) => {}
}
match (old_preprocessing_id, &updated_attempt.preprocessing_step_id) {
(None, Some(preprocessing_id)) => {
add_preprocessing_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.attempt_id.as_str(),
preprocessing_id.as_str(),
storage_scheme,
)
.await?;
}
(Some(old_preprocessing_id), Some(preprocessing_id)) => {
if old_preprocessing_id.ne(preprocessing_id) {
add_preprocessing_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.attempt_id.as_str(),
preprocessing_id.as_str(),
storage_scheme,
)
.await?;
}
}
(_, _) => {}
}
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), redis_entry),
key,
))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hset()
.change_context(errors::StorageError::KVError)?;
Ok(updated_attempt)
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
// Ignoring storage scheme for v2 implementation
self.router_store
.update_payment_attempt(
key_manager_state,
merchant_key_store,
this,
payment_attempt,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&self,
connector_transaction_id: &ConnectorTransactionId,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
connector_transaction_id,
payment_id,
merchant_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
// We assume that PaymentAttempt <=> PaymentIntent is a one-to-one relation for now
let lookup_id = format!(
"pa_conn_trans_{}_{}",
merchant_id.get_string_repr(),
connector_transaction_id.get_id()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
connector_transaction_id,
payment_id,
merchant_id,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key)).await?.try_into_hget()
},
|| async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme).await},
))
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let database_call = || {
self.router_store
.find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
payment_id,
merchant_id,
storage_scheme,
)
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
let pattern = "pa_*";
let redis_fut = async {
let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
self,
KvOperation::<DieselPaymentAttempt>::Scan(pattern),
key,
))
.await?
.try_into_scan();
kv_result.and_then(|mut payment_attempts| {
payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at));
payment_attempts
.iter()
.find(|&pa| pa.status == api_models::enums::AttemptStatus::Charged)
.cloned()
.ok_or(error_stack::report!(
redis_interface::errors::RedisError::NotFound
))
})
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
database_call,
))
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let database_call = || {
self.router_store
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
payment_id,
merchant_id,
storage_scheme,
)
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
let pattern = "pa_*";
let redis_fut = async {
let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
self,
KvOperation::<DieselPaymentAttempt>::Scan(pattern),
key,
))
.await?
.try_into_scan();
kv_result.and_then(|mut payment_attempts| {
payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at));
payment_attempts
.iter()
.find(|&pa| {
pa.status == api_models::enums::AttemptStatus::Charged
|| pa.status == api_models::enums::AttemptStatus::PartialCharged
})
.cloned()
.ok_or(error_stack::report!(
redis_interface::errors::RedisError::NotFound
))
})
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
database_call,
))
.await
}
}
}
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_profile_id_connector_transaction_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
connector_transaction_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
// Ignoring storage scheme for v2 implementation
self.router_store
.find_payment_attempt_by_profile_id_connector_transaction_id(
key_manager_state,
merchant_key_store,
profile_id,
connector_transaction_id,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
connector_txn_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"pa_conn_trans_{}_{connector_txn_id}",
merchant_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
connector_txn_id,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
connector_txn_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_id,
merchant_id,
attempt_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
let field = format!("pa_{attempt_id}");
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_id,
merchant_id,
attempt_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_attempt_by_attempt_id_merchant_id(
attempt_id,
merchant_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id = format!("pa_{}_{attempt_id}", merchant_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payment_attempt_by_attempt_id_merchant_id(
attempt_id,
merchant_id,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payment_attempt_by_attempt_id_merchant_id(
attempt_id,
merchant_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
attempt_id: &common_utils::id_type::GlobalAttemptId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
// Ignoring storage scheme for v2 implementation
self.router_store
.find_payment_attempt_by_id(
key_manager_state,
merchant_key_store,
attempt_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_attempts_by_payment_intent_id(
&self,
key_manager_state: &KeyManagerState,
payment_id: &common_utils::id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
self.router_store
.find_payment_attempts_by_payment_intent_id(
key_manager_state,
payment_id,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_attempt_by_preprocessing_id_merchant_id(
preprocessing_id,
merchant_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"pa_preprocessing_{}_{preprocessing_id}",
merchant_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payment_attempt_by_preprocessing_id_merchant_id(
preprocessing_id,
merchant_id,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payment_attempt_by_preprocessing_id_merchant_id(
preprocessing_id,
merchant_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_attempts_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_attempts_by_merchant_id_payment_id(
merchant_id,
payment_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::Scan("pa_*"),
key,
))
.await?
.try_into_scan()
},
|| async {
self.router_store
.find_attempts_by_merchant_id_payment_id(
merchant_id,
payment_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filters_for_payments(
&self,
pi: &[PaymentIntent],
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentListFilters, errors::StorageError> {
self.router_store
.get_filters_for_payments(pi, merchant_id, storage_scheme)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<api_models::enums::Connector>>,
payment_method: Option<Vec<common_enums::PaymentMethod>>,
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<common_enums::CardNetwork>>,
card_discovery: Option<Vec<common_enums::CardDiscovery>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
.get_total_count_of_filtered_payment_attempts(
merchant_id,
active_attempt_ids,
connector,
payment_method,
payment_method_type,
authentication_type,
merchant_connector_id,
card_network,
card_discovery,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<api_models::enums::Connector>,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
card_network: Option<common_enums::CardNetwork>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
.get_total_count_of_filtered_payment_attempts(
merchant_id,
active_attempt_ids,
connector,
payment_method_type,
payment_method_subtype,
authentication_type,
merchant_connector_id,
card_network,
storage_scheme,
)
.await
}
}
impl DataModelExt for MandateAmountData {
type StorageModel = DieselMandateAmountData;
fn to_storage_model(self) -> Self::StorageModel {
DieselMandateAmountData {
amount: self.amount,
currency: self.currency,
start_date: self.start_date,
end_date: self.end_date,
metadata: self.metadata,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
amount: storage_model.amount,
currency: storage_model.currency,
start_date: storage_model.start_date,
end_date: storage_model.end_date,
metadata: storage_model.metadata,
}
}
}
impl DataModelExt for MandateDetails {
type StorageModel = DieselMandateDetails;
fn to_storage_model(self) -> Self::StorageModel {
DieselMandateDetails {
update_mandate_id: self.update_mandate_id,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
update_mandate_id: storage_model.update_mandate_id,
}
}
}
impl DataModelExt for MandateDataType {
type StorageModel = DieselMandateType;
fn to_storage_model(self) -> Self::StorageModel {
match self {
Self::SingleUse(data) => DieselMandateType::SingleUse(data.to_storage_model()),
Self::MultiUse(None) => DieselMandateType::MultiUse(None),
Self::MultiUse(Some(data)) => {
DieselMandateType::MultiUse(Some(data.to_storage_model()))
}
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
match storage_model {
DieselMandateType::SingleUse(data) => {
Self::SingleUse(MandateAmountData::from_storage_model(data))
}
DieselMandateType::MultiUse(Some(data)) => {
Self::MultiUse(Some(MandateAmountData::from_storage_model(data)))
}
DieselMandateType::MultiUse(None) => Self::MultiUse(None),
}
}
}
#[cfg(feature = "v1")]
impl DataModelExt for PaymentAttempt {
type StorageModel = DieselPaymentAttempt;
fn to_storage_model(self) -> Self::StorageModel {
let (connector_transaction_id, processor_transaction_data) = self
.connector_transaction_id
.map(ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
DieselPaymentAttempt {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
status: self.status,
amount: self.net_amount.get_order_amount(),
net_amount: Some(self.net_amount.get_total_amount()),
currency: self.currency,
save_to_locker: self.save_to_locker,
connector: self.connector,
error_message: self.error_message,
offer_amount: self.offer_amount,
surcharge_amount: self.net_amount.get_surcharge_amount(),
tax_amount: self.net_amount.get_tax_on_surcharge(),
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
connector_transaction_id,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
authentication_type: self.authentication_type,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
cancellation_reason: self.cancellation_reason,
amount_to_capture: self.amount_to_capture,
mandate_id: self.mandate_id,
browser_info: self.browser_info,
error_code: self.error_code,
payment_token: self.payment_token,
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
card_network: self
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
mandate_details: self.mandate_details.map(|d| d.to_storage_model()),
error_reason: self.error_reason,
multiple_capture_count: self.multiple_capture_count,
connector_response_reference_id: self.connector_response_reference_id,
amount_capturable: self.amount_capturable,
updated_by: self.updated_by,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
merchant_connector_id: self.merchant_connector_id,
unified_code: self.unified_code,
unified_message: self.unified_message,
external_three_ds_authentication_attempted: self
.external_three_ds_authentication_attempted,
authentication_connector: self.authentication_connector,
authentication_id: self.authentication_id,
mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
payment_method_billing_address_id: self.payment_method_billing_address_id,
fingerprint_id: self.fingerprint_id,
charge_id: self.charge_id,
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
organization_id: self.organization_id,
profile_id: self.profile_id,
shipping_cost: self.net_amount.get_shipping_cost(),
order_tax_amount: self.net_amount.get_order_tax_amount(),
connector_mandate_detail: self.connector_mandate_detail,
request_extended_authorization: self.request_extended_authorization,
extended_authorization_applied: self.extended_authorization_applied,
capture_before: self.capture_before,
processor_transaction_data,
card_discovery: self.card_discovery,
charges: self.charges,
issuer_error_code: self.issuer_error_code,
issuer_error_message: self.issuer_error_message,
// Below fields are deprecated. Please add any new fields above this line.
connector_transaction_data: None,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
let connector_transaction_id = storage_model
.get_optional_connector_transaction_id()
.cloned();
Self {
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
storage_model.amount,
storage_model.shipping_cost,
storage_model.order_tax_amount,
storage_model.surcharge_amount,
storage_model.tax_amount,
),
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
attempt_id: storage_model.attempt_id,
status: storage_model.status,
currency: storage_model.currency,
save_to_locker: storage_model.save_to_locker,
connector: storage_model.connector,
error_message: storage_model.error_message,
offer_amount: storage_model.offer_amount,
payment_method_id: storage_model.payment_method_id,
payment_method: storage_model.payment_method,
connector_transaction_id,
capture_method: storage_model.capture_method,
capture_on: storage_model.capture_on,
confirm: storage_model.confirm,
authentication_type: storage_model.authentication_type,
created_at: storage_model.created_at,
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
cancellation_reason: storage_model.cancellation_reason,
amount_to_capture: storage_model.amount_to_capture,
mandate_id: storage_model.mandate_id,
browser_info: storage_model.browser_info,
error_code: storage_model.error_code,
payment_token: storage_model.payment_token,
connector_metadata: storage_model.connector_metadata,
payment_experience: storage_model.payment_experience,
payment_method_type: storage_model.payment_method_type,
payment_method_data: storage_model.payment_method_data,
business_sub_label: storage_model.business_sub_label,
straight_through_algorithm: storage_model.straight_through_algorithm,
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model
.mandate_details
.map(MandateDataType::from_storage_model),
error_reason: storage_model.error_reason,
multiple_capture_count: storage_model.multiple_capture_count,
connector_response_reference_id: storage_model.connector_response_reference_id,
amount_capturable: storage_model.amount_capturable,
updated_by: storage_model.updated_by,
authentication_data: storage_model.authentication_data,
encoded_data: storage_model.encoded_data,
merchant_connector_id: storage_model.merchant_connector_id,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
external_three_ds_authentication_attempted: storage_model
.external_three_ds_authentication_attempted,
authentication_connector: storage_model.authentication_connector,
authentication_id: storage_model.authentication_id,
mandate_data: storage_model
.mandate_data
.map(MandateDetails::from_storage_model),
payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
fingerprint_id: storage_model.fingerprint_id,
charge_id: storage_model.charge_id,
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
connector_mandate_detail: storage_model.connector_mandate_detail,
request_extended_authorization: storage_model.request_extended_authorization,
extended_authorization_applied: storage_model.extended_authorization_applied,
capture_before: storage_model.capture_before,
card_discovery: storage_model.card_discovery,
charges: storage_model.charges,
issuer_error_code: storage_model.issuer_error_code,
issuer_error_message: storage_model.issuer_error_message,
}
}
}
#[cfg(feature = "v1")]
impl DataModelExt for PaymentAttemptNew {
type StorageModel = DieselPaymentAttemptNew;
fn to_storage_model(self) -> Self::StorageModel {
DieselPaymentAttemptNew {
net_amount: Some(self.net_amount.get_total_amount()),
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
status: self.status,
amount: self.net_amount.get_order_amount(),
currency: self.currency,
save_to_locker: self.save_to_locker,
connector: self.connector,
error_message: self.error_message,
offer_amount: self.offer_amount,
surcharge_amount: self.net_amount.get_surcharge_amount(),
tax_amount: self.net_amount.get_tax_on_surcharge(),
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
authentication_type: self.authentication_type,
created_at: self.created_at.unwrap_or_else(common_utils::date_time::now),
modified_at: self
.modified_at
.unwrap_or_else(common_utils::date_time::now),
last_synced: self.last_synced,
cancellation_reason: self.cancellation_reason,
amount_to_capture: self.amount_to_capture,
mandate_id: self.mandate_id,
browser_info: self.browser_info,
payment_token: self.payment_token,
error_code: self.error_code,
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
card_network: self
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|value| value.as_object())
.and_then(|map| map.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
mandate_details: self.mandate_details.map(|d| d.to_storage_model()),
error_reason: self.error_reason,
connector_response_reference_id: self.connector_response_reference_id,
multiple_capture_count: self.multiple_capture_count,
amount_capturable: self.amount_capturable,
updated_by: self.updated_by,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
merchant_connector_id: self.merchant_connector_id,
unified_code: self.unified_code,
unified_message: self.unified_message,
external_three_ds_authentication_attempted: self
.external_three_ds_authentication_attempted,
authentication_connector: self.authentication_connector,
authentication_id: self.authentication_id,
mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
payment_method_billing_address_id: self.payment_method_billing_address_id,
fingerprint_id: self.fingerprint_id,
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
organization_id: self.organization_id,
profile_id: self.profile_id,
shipping_cost: self.net_amount.get_shipping_cost(),
order_tax_amount: self.net_amount.get_order_tax_amount(),
connector_mandate_detail: self.connector_mandate_detail,
request_extended_authorization: self.request_extended_authorization,
extended_authorization_applied: self.extended_authorization_applied,
capture_before: self.capture_before,
card_discovery: self.card_discovery,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
storage_model.amount,
storage_model.shipping_cost,
storage_model.order_tax_amount,
storage_model.surcharge_amount,
storage_model.tax_amount,
),
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
attempt_id: storage_model.attempt_id,
status: storage_model.status,
currency: storage_model.currency,
save_to_locker: storage_model.save_to_locker,
connector: storage_model.connector,
error_message: storage_model.error_message,
offer_amount: storage_model.offer_amount,
payment_method_id: storage_model.payment_method_id,
payment_method: storage_model.payment_method,
capture_method: storage_model.capture_method,
capture_on: storage_model.capture_on,
confirm: storage_model.confirm,
authentication_type: storage_model.authentication_type,
created_at: Some(storage_model.created_at),
modified_at: Some(storage_model.modified_at),
last_synced: storage_model.last_synced,
cancellation_reason: storage_model.cancellation_reason,
amount_to_capture: storage_model.amount_to_capture,
mandate_id: storage_model.mandate_id,
browser_info: storage_model.browser_info,
payment_token: storage_model.payment_token,
error_code: storage_model.error_code,
connector_metadata: storage_model.connector_metadata,
payment_experience: storage_model.payment_experience,
payment_method_type: storage_model.payment_method_type,
payment_method_data: storage_model.payment_method_data,
business_sub_label: storage_model.business_sub_label,
straight_through_algorithm: storage_model.straight_through_algorithm,
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model
.mandate_details
.map(MandateDataType::from_storage_model),
error_reason: storage_model.error_reason,
connector_response_reference_id: storage_model.connector_response_reference_id,
multiple_capture_count: storage_model.multiple_capture_count,
amount_capturable: storage_model.amount_capturable,
updated_by: storage_model.updated_by,
authentication_data: storage_model.authentication_data,
encoded_data: storage_model.encoded_data,
merchant_connector_id: storage_model.merchant_connector_id,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
external_three_ds_authentication_attempted: storage_model
.external_three_ds_authentication_attempted,
authentication_connector: storage_model.authentication_connector,
authentication_id: storage_model.authentication_id,
mandate_data: storage_model
.mandate_data
.map(MandateDetails::from_storage_model),
payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
fingerprint_id: storage_model.fingerprint_id,
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
connector_mandate_detail: storage_model.connector_mandate_detail,
request_extended_authorization: storage_model.request_extended_authorization,
extended_authorization_applied: storage_model.extended_authorization_applied,
capture_before: storage_model.capture_before,
card_discovery: storage_model.card_discovery,
}
}
}
#[inline]
#[instrument(skip_all)]
async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
connector_transaction_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("pa_{}", updated_attempt_attempt_id);
let reverse_lookup_new = ReverseLookupNew {
lookup_id: format!(
"pa_conn_trans_{}_{}",
merchant_id.get_string_repr(),
connector_transaction_id
),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payment_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
store
.insert_reverse_lookup(reverse_lookup_new, storage_scheme)
.await
}
#[inline]
#[instrument(skip_all)]
async fn add_preprocessing_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
preprocessing_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("pa_{}", updated_attempt_attempt_id);
let reverse_lookup_new = ReverseLookupNew {
lookup_id: format!(
"pa_preprocessing_{}_{}",
merchant_id.get_string_repr(),
preprocessing_id
),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payment_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
store
.insert_reverse_lookup(reverse_lookup_new, storage_scheme)
.await
}
| 14,754 | 1,050 |
hyperswitch | crates/storage_impl/src/database/store.rs | .rs | use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::CustomizeConnection;
use common_utils::DbConnectionParams;
use diesel::PgConnection;
use error_stack::ResultExt;
use crate::{
config::{Database, TenantConfig},
errors::{StorageError, StorageResult},
};
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
#[async_trait::async_trait]
pub trait DatabaseStore: Clone + Send + Sync {
type Config: Send;
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> StorageResult<Self>;
fn get_master_pool(&self) -> &PgPool;
fn get_replica_pool(&self) -> &PgPool;
fn get_accounts_master_pool(&self) -> &PgPool;
fn get_accounts_replica_pool(&self) -> &PgPool;
}
#[derive(Debug, Clone)]
pub struct Store {
pub master_pool: PgPool,
pub accounts_pool: PgPool,
}
#[async_trait::async_trait]
impl DatabaseStore for Store {
type Config = Database;
async fn new(
config: Database,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> StorageResult<Self> {
Ok(Self {
master_pool: diesel_make_pg_pool(&config, tenant_config.get_schema(), test_transaction)
.await?,
accounts_pool: diesel_make_pg_pool(
&config,
tenant_config.get_accounts_schema(),
test_transaction,
)
.await?,
})
}
fn get_master_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_replica_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_accounts_master_pool(&self) -> &PgPool {
&self.accounts_pool
}
fn get_accounts_replica_pool(&self) -> &PgPool {
&self.accounts_pool
}
}
#[derive(Debug, Clone)]
pub struct ReplicaStore {
pub master_pool: PgPool,
pub replica_pool: PgPool,
pub accounts_master_pool: PgPool,
pub accounts_replica_pool: PgPool,
}
#[async_trait::async_trait]
impl DatabaseStore for ReplicaStore {
type Config = (Database, Database);
async fn new(
config: (Database, Database),
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> StorageResult<Self> {
let (master_config, replica_config) = config;
let master_pool =
diesel_make_pg_pool(&master_config, tenant_config.get_schema(), test_transaction)
.await
.attach_printable("failed to create master pool")?;
let accounts_master_pool = diesel_make_pg_pool(
&master_config,
tenant_config.get_accounts_schema(),
test_transaction,
)
.await
.attach_printable("failed to create accounts master pool")?;
let replica_pool = diesel_make_pg_pool(
&replica_config,
tenant_config.get_schema(),
test_transaction,
)
.await
.attach_printable("failed to create replica pool")?;
let accounts_replica_pool = diesel_make_pg_pool(
&replica_config,
tenant_config.get_accounts_schema(),
test_transaction,
)
.await
.attach_printable("failed to create accounts pool")?;
Ok(Self {
master_pool,
replica_pool,
accounts_master_pool,
accounts_replica_pool,
})
}
fn get_master_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_replica_pool(&self) -> &PgPool {
&self.replica_pool
}
fn get_accounts_master_pool(&self) -> &PgPool {
&self.accounts_master_pool
}
fn get_accounts_replica_pool(&self) -> &PgPool {
&self.accounts_replica_pool
}
}
pub async fn diesel_make_pg_pool(
database: &Database,
schema: &str,
test_transaction: bool,
) -> StorageResult<PgPool> {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let mut pool = bb8::Pool::builder()
.max_size(database.pool_size)
.min_idle(database.min_idle)
.queue_strategy(database.queue_strategy.into())
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout))
.max_lifetime(database.max_lifetime.map(std::time::Duration::from_secs));
if test_transaction {
pool = pool.connection_customizer(Box::new(TestTransaction));
}
pool.build(manager)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to create PostgreSQL connection pool")
}
#[derive(Debug)]
struct TestTransaction;
#[async_trait::async_trait]
impl CustomizeConnection<PgPooledConn, ConnectionError> for TestTransaction {
#[allow(clippy::unwrap_used)]
async fn on_acquire(&self, conn: &mut PgPooledConn) -> Result<(), ConnectionError> {
use diesel::Connection;
conn.run(|conn| {
conn.begin_test_transaction().unwrap();
Ok(())
})
.await
}
}
| 1,151 | 1,051 |
hyperswitch | crates/storage_impl/src/redis/cache.rs | .rs | use std::{any::Any, borrow::Cow, fmt::Debug, sync::Arc};
use common_utils::{
errors::{self, CustomResult},
ext_traits::ByteSliceExt,
};
use dyn_clone::DynClone;
use error_stack::{Report, ResultExt};
use moka::future::Cache as MokaCache;
use once_cell::sync::Lazy;
use redis_interface::{errors::RedisError, RedisConnectionPool, RedisValue};
use router_env::{
logger,
tracing::{self, instrument},
};
use crate::{
errors::StorageError,
metrics,
redis::{PubSubInterface, RedisConnInterface},
};
/// Redis channel name used for publishing invalidation messages
pub const IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate";
/// Time to live 30 mins
const CACHE_TTL: u64 = 30 * 60;
/// Time to idle 10 mins
const CACHE_TTI: u64 = 10 * 60;
/// Max Capacity of Cache in MB
const MAX_CAPACITY: u64 = 30;
/// Config Cache with time_to_live as 30 mins and time_to_idle as 10 mins.
pub static CONFIG_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new("CONFIG_CACHE", CACHE_TTL, CACHE_TTI, None));
/// Accounts cache with time_to_live as 30 mins and size limit
pub static ACCOUNTS_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new("ACCOUNTS_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// Routing Cache
pub static ROUTING_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new("ROUTING_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// 3DS Decision Manager Cache
pub static DECISION_MANAGER_CACHE: Lazy<Cache> = Lazy::new(|| {
Cache::new(
"DECISION_MANAGER_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Surcharge Cache
pub static SURCHARGE_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new("SURCHARGE_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// CGraph Cache
pub static CGRAPH_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new("CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// PM Filter CGraph Cache
pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> = Lazy::new(|| {
Cache::new(
"PM_FILTERS_CGRAPH_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Success based Dynamic Algorithm Cache
pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
Cache::new(
"SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Elimination based Dynamic Algorithm Cache
pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
Cache::new(
"ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Contract Routing based Dynamic Algorithm Cache
pub static CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
Cache::new(
"CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CacheRedact<'a> {
pub tenant: String,
pub kind: CacheKind<'a>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum CacheKind<'a> {
Config(Cow<'a, str>),
Accounts(Cow<'a, str>),
Routing(Cow<'a, str>),
DecisionManager(Cow<'a, str>),
Surcharge(Cow<'a, str>),
CGraph(Cow<'a, str>),
SuccessBasedDynamicRoutingCache(Cow<'a, str>),
EliminationBasedDynamicRoutingCache(Cow<'a, str>),
ContractBasedDynamicRoutingCache(Cow<'a, str>),
PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
}
impl CacheKind<'_> {
pub(crate) fn get_key_without_prefix(&self) -> &str {
match self {
CacheKind::Config(key)
| CacheKind::Accounts(key)
| CacheKind::Routing(key)
| CacheKind::DecisionManager(key)
| CacheKind::Surcharge(key)
| CacheKind::CGraph(key)
| CacheKind::SuccessBasedDynamicRoutingCache(key)
| CacheKind::EliminationBasedDynamicRoutingCache(key)
| CacheKind::ContractBasedDynamicRoutingCache(key)
| CacheKind::PmFiltersCGraph(key)
| CacheKind::All(key) => key,
}
}
}
impl<'a> TryFrom<CacheRedact<'a>> for RedisValue {
type Error = Report<errors::ValidationError>;
fn try_from(v: CacheRedact<'a>) -> Result<Self, Self::Error> {
Ok(Self::from_bytes(serde_json::to_vec(&v).change_context(
errors::ValidationError::InvalidValue {
message: "Invalid publish key provided in pubsub".into(),
},
)?))
}
}
impl TryFrom<RedisValue> for CacheRedact<'_> {
type Error = Report<errors::ValidationError>;
fn try_from(v: RedisValue) -> Result<Self, Self::Error> {
let bytes = v.as_bytes().ok_or(errors::ValidationError::InvalidValue {
message: "InvalidValue received in pubsub".to_string(),
})?;
bytes
.parse_struct("CacheRedact")
.change_context(errors::ValidationError::InvalidValue {
message: "Unable to deserialize the value from pubsub".to_string(),
})
}
}
impl<T> Cacheable for T
where
T: Any + Clone + Send + Sync,
{
fn as_any(&self) -> &dyn Any {
self
}
}
dyn_clone::clone_trait_object!(Cacheable);
pub struct Cache {
name: &'static str,
inner: MokaCache<String, Arc<dyn Cacheable>>,
}
#[derive(Debug, Clone)]
pub struct CacheKey {
pub key: String,
// #TODO: make it usage specific enum Eg: CacheKind { Tenant(String), NoTenant, Partition(String) }
pub prefix: String,
}
impl From<CacheKey> for String {
fn from(val: CacheKey) -> Self {
if val.prefix.is_empty() {
val.key
} else {
format!("{}:{}", val.prefix, val.key)
}
}
}
impl Cache {
/// With given `time_to_live` and `time_to_idle` creates a moka cache.
///
/// `name` : Cache type name to be used as an attribute in metrics
/// `time_to_live`: Time in seconds before an object is stored in a caching system before it’s deleted
/// `time_to_idle`: Time in seconds before a `get` or `insert` operation an object is stored in a caching system before it's deleted
/// `max_capacity`: Max size in MB's that the cache can hold
pub fn new(
name: &'static str,
time_to_live: u64,
time_to_idle: u64,
max_capacity: Option<u64>,
) -> Self {
// Record the metrics of manual invalidation of cache entry by the application
let eviction_listener = move |_, _, cause| {
metrics::IN_MEMORY_CACHE_EVICTION_COUNT.add(
1,
router_env::metric_attributes!(
("cache_type", name.to_owned()),
("removal_cause", format!("{:?}", cause)),
),
);
};
let mut cache_builder = MokaCache::builder()
.time_to_live(std::time::Duration::from_secs(time_to_live))
.time_to_idle(std::time::Duration::from_secs(time_to_idle))
.eviction_listener(eviction_listener);
if let Some(capacity) = max_capacity {
cache_builder = cache_builder.max_capacity(capacity * 1024 * 1024);
}
Self {
name,
inner: cache_builder.build(),
}
}
pub async fn push<T: Cacheable>(&self, key: CacheKey, val: T) {
self.inner.insert(key.into(), Arc::new(val)).await;
}
pub async fn get_val<T: Clone + Cacheable>(&self, key: CacheKey) -> Option<T> {
let val = self.inner.get::<String>(&key.into()).await;
// Add cache hit and cache miss metrics
if val.is_some() {
metrics::IN_MEMORY_CACHE_HIT
.add(1, router_env::metric_attributes!(("cache_type", self.name)));
} else {
metrics::IN_MEMORY_CACHE_MISS
.add(1, router_env::metric_attributes!(("cache_type", self.name)));
}
let val = (*val?).as_any().downcast_ref::<T>().cloned();
val
}
/// Check if a key exists in cache
pub async fn exists(&self, key: CacheKey) -> bool {
self.inner.contains_key::<String>(&key.into())
}
pub async fn remove(&self, key: CacheKey) {
self.inner.invalidate::<String>(&key.into()).await;
}
/// Performs any pending maintenance operations needed by the cache.
async fn run_pending_tasks(&self) {
self.inner.run_pending_tasks().await;
}
/// Returns an approximate number of entries in this cache.
fn get_entry_count(&self) -> u64 {
self.inner.entry_count()
}
pub fn name(&self) -> &'static str {
self.name
}
pub async fn record_entry_count_metric(&self) {
self.run_pending_tasks().await;
metrics::IN_MEMORY_CACHE_ENTRY_COUNT.record(
self.get_entry_count(),
router_env::metric_attributes!(("cache_type", self.name)),
);
}
}
#[instrument(skip_all)]
pub async fn get_or_populate_redis<T, F, Fut>(
redis: &Arc<RedisConnectionPool>,
key: impl AsRef<str>,
fun: F,
) -> CustomResult<T, StorageError>
where
T: serde::Serialize + serde::de::DeserializeOwned + Debug,
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let type_name = std::any::type_name::<T>();
let key = key.as_ref();
let redis_val = redis
.get_and_deserialize_key::<T>(&key.into(), type_name)
.await;
let get_data_set_redis = || async {
let data = fun().await?;
redis
.serialize_and_set_key(&key.into(), &data)
.await
.change_context(StorageError::KVError)?;
Ok::<_, Report<StorageError>>(data)
};
match redis_val {
Err(err) => match err.current_context() {
RedisError::NotFound | RedisError::JsonDeserializationFailed => {
get_data_set_redis().await
}
_ => Err(err
.change_context(StorageError::KVError)
.attach_printable(format!("Error while fetching cache for {type_name}"))),
},
Ok(val) => Ok(val),
}
}
#[instrument(skip_all)]
pub async fn get_or_populate_in_memory<T, F, Fut>(
store: &(dyn RedisConnInterface + Send + Sync),
key: &str,
fun: F,
cache: &Cache,
) -> CustomResult<T, StorageError>
where
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let redis = &store
.get_redis_conn()
.change_context(StorageError::RedisError(
RedisError::RedisConnectionError.into(),
))
.attach_printable("Failed to get redis connection")?;
let cache_val = cache
.get_val::<T>(CacheKey {
key: key.to_string(),
prefix: redis.key_prefix.clone(),
})
.await;
if let Some(val) = cache_val {
Ok(val)
} else {
let val = get_or_populate_redis(redis, key, fun).await?;
cache
.push(
CacheKey {
key: key.to_string(),
prefix: redis.key_prefix.clone(),
},
val.clone(),
)
.await;
Ok(val)
}
}
#[instrument(skip_all)]
pub async fn redact_from_redis_and_publish<
'a,
K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
>(
store: &(dyn RedisConnInterface + Send + Sync),
keys: K,
) -> CustomResult<usize, StorageError> {
let redis_conn = store
.get_redis_conn()
.change_context(StorageError::RedisError(
RedisError::RedisConnectionError.into(),
))
.attach_printable("Failed to get redis connection")?;
let redis_keys_to_be_deleted = keys
.clone()
.into_iter()
.map(|val| val.get_key_without_prefix().to_owned().into())
.collect::<Vec<_>>();
let del_replies = redis_conn
.delete_multiple_keys(&redis_keys_to_be_deleted)
.await
.map_err(StorageError::RedisError)?;
let deletion_result = redis_keys_to_be_deleted
.into_iter()
.zip(del_replies)
.collect::<Vec<_>>();
logger::debug!(redis_deletion_result=?deletion_result);
let futures = keys.into_iter().map(|key| async {
redis_conn
.clone()
.publish(IMC_INVALIDATION_CHANNEL, key)
.await
.change_context(StorageError::KVError)
});
Ok(futures::future::try_join_all(futures)
.await?
.iter()
.sum::<usize>())
}
#[instrument(skip_all)]
pub async fn publish_and_redact<'a, T, F, Fut>(
store: &(dyn RedisConnInterface + Send + Sync),
key: CacheKind<'a>,
fun: F,
) -> CustomResult<T, StorageError>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let data = fun().await?;
redact_from_redis_and_publish(store, [key]).await?;
Ok(data)
}
#[instrument(skip_all)]
pub async fn publish_and_redact_multiple<'a, T, F, Fut, K>(
store: &(dyn RedisConnInterface + Send + Sync),
keys: K,
fun: F,
) -> CustomResult<T, StorageError>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
{
let data = fun().await?;
redact_from_redis_and_publish(store, keys).await?;
Ok(data)
}
#[cfg(test)]
mod cache_tests {
use super::*;
#[tokio::test]
async fn construct_and_get_cache() {
let cache = Cache::new("test", 1800, 1800, None);
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
Some(String::from("val"))
);
}
#[tokio::test]
async fn eviction_on_size_test() {
let cache = Cache::new("test", 2, 2, Some(0));
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
None
);
}
#[tokio::test]
async fn invalidate_cache_for_key() {
let cache = Cache::new("test", 1800, 1800, None);
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
cache
.remove(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
})
.await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
None
);
}
#[tokio::test]
async fn eviction_on_time_test() {
let cache = Cache::new("test", 2, 2, None);
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
None
);
}
}
| 3,997 | 1,052 |
hyperswitch | crates/storage_impl/src/redis/pub_sub.rs | .rs | use std::sync::atomic;
use error_stack::ResultExt;
use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue};
use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE,
CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE,
ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE,
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
pub trait PubSubInterface {
async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError>;
async fn publish<'a>(
&self,
channel: &str,
key: CacheKind<'a>,
) -> error_stack::Result<usize, redis_errors::RedisError>;
async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError>;
}
#[async_trait::async_trait]
impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
#[inline]
async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> {
// Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client.
self.subscriber.manage_subscriptions();
self.subscriber
.subscribe::<(), &str>(channel)
.await
.change_context(redis_errors::RedisError::SubscribeError)?;
// Spawn only one thread handling all the published messages to different channels
if self
.subscriber
.is_subscriber_handler_spawned
.compare_exchange(
false,
true,
atomic::Ordering::SeqCst,
atomic::Ordering::SeqCst,
)
.is_ok()
{
let redis_clone = self.clone();
let _task_handle = tokio::spawn(
async move {
if let Err(pubsub_error) = redis_clone.on_message().await {
logger::error!(?pubsub_error);
}
}
.in_current_span(),
);
}
Ok(())
}
#[inline]
async fn publish<'a>(
&self,
channel: &str,
key: CacheKind<'a>,
) -> error_stack::Result<usize, redis_errors::RedisError> {
let key = CacheRedact {
kind: key,
tenant: self.key_prefix.clone(),
};
self.publisher
.publish(
channel,
RedisValue::try_from(key).change_context(redis_errors::RedisError::PublishError)?,
)
.await
.change_context(redis_errors::RedisError::SubscribeError)
}
#[inline]
async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> {
logger::debug!("Started on message");
let mut rx = self.subscriber.on_message();
while let Ok(message) = rx.recv().await {
let channel_name = message.channel.to_string();
logger::debug!("Received message on channel: {channel_name}");
match channel_name.as_str() {
super::cache::IMC_INVALIDATION_CHANNEL => {
let message = match CacheRedact::try_from(RedisValue::new(message.value))
.change_context(redis_errors::RedisError::OnMessageError)
{
Ok(value) => value,
Err(err) => {
logger::error!(value_conversion_err=?err);
continue;
}
};
let key = match message.kind {
CacheKind::Config(key) => {
CONFIG_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::Accounts(key) => {
ACCOUNTS_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::CGraph(key) => {
CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::PmFiltersCGraph(key) => {
PM_FILTERS_CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::EliminationBasedDynamicRoutingCache(key) => {
ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::ContractBasedDynamicRoutingCache(key) => {
CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::SuccessBasedDynamicRoutingCache(key) => {
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::Routing(key) => {
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::DecisionManager(key) => {
DECISION_MANAGER_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::Surcharge(key) => {
SURCHARGE_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::All(key) => {
CONFIG_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
ACCOUNTS_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
PM_FILTERS_CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
DECISION_MANAGER_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
SURCHARGE_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
};
logger::debug!(
key_prefix=?message.tenant.clone(),
channel_name=?channel_name,
"Done invalidating {key}"
);
}
_ => {
logger::debug!("Received message from unknown channel: {channel_name}");
}
}
}
Ok(())
}
}
| 1,710 | 1,053 |
hyperswitch | crates/storage_impl/src/redis/kv_store.rs | .rs | use std::{fmt::Debug, sync::Arc};
use common_utils::errors::CustomResult;
use diesel_models::enums::MerchantStorageScheme;
use error_stack::report;
use redis_interface::errors::RedisError;
use router_derive::TryGetEnumVariant;
use router_env::logger;
use serde::de;
use crate::{kv_router_store::KVRouterStore, metrics, store::kv::TypedSql, UniqueConstraints};
pub trait KvStorePartition {
fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 {
crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions)
}
fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String {
format!("shard_{}", Self::partition_number(key, num_partitions))
}
}
#[allow(unused)]
#[derive(Clone)]
pub enum PartitionKey<'a> {
MerchantIdPaymentId {
merchant_id: &'a common_utils::id_type::MerchantId,
payment_id: &'a common_utils::id_type::PaymentId,
},
CombinationKey {
combination: &'a str,
},
MerchantIdCustomerId {
merchant_id: &'a common_utils::id_type::MerchantId,
customer_id: &'a common_utils::id_type::CustomerId,
},
#[cfg(all(feature = "v2", feature = "customer_v2"))]
MerchantIdMerchantReferenceId {
merchant_id: &'a common_utils::id_type::MerchantId,
merchant_reference_id: &'a str,
},
MerchantIdPayoutId {
merchant_id: &'a common_utils::id_type::MerchantId,
payout_id: &'a str,
},
MerchantIdPayoutAttemptId {
merchant_id: &'a common_utils::id_type::MerchantId,
payout_attempt_id: &'a str,
},
MerchantIdMandateId {
merchant_id: &'a common_utils::id_type::MerchantId,
mandate_id: &'a str,
},
#[cfg(all(feature = "v2", feature = "customer_v2"))]
GlobalId {
id: &'a str,
},
}
// PartitionKey::MerchantIdPaymentId {merchant_id, payment_id}
impl std::fmt::Display for PartitionKey<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
} => f.write_str(&format!(
"mid_{}_pid_{}",
merchant_id.get_string_repr(),
payment_id.get_string_repr()
)),
PartitionKey::CombinationKey { combination } => f.write_str(combination),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
} => f.write_str(&format!(
"mid_{}_cust_{}",
merchant_id.get_string_repr(),
customer_id.get_string_repr()
)),
#[cfg(all(feature = "v2", feature = "customer_v2"))]
PartitionKey::MerchantIdMerchantReferenceId {
merchant_id,
merchant_reference_id,
} => f.write_str(&format!(
"mid_{}_cust_{merchant_reference_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
} => f.write_str(&format!(
"mid_{}_po_{payout_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdPayoutAttemptId {
merchant_id,
payout_attempt_id,
} => f.write_str(&format!(
"mid_{}_poa_{payout_attempt_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id,
} => f.write_str(&format!(
"mid_{}_mandate_{mandate_id}",
merchant_id.get_string_repr()
)),
#[cfg(all(feature = "v2", feature = "customer_v2"))]
PartitionKey::GlobalId { id } => f.write_str(&format!("cust_{id}",)),
}
}
}
pub trait RedisConnInterface {
fn get_redis_conn(
&self,
) -> error_stack::Result<Arc<redis_interface::RedisConnectionPool>, RedisError>;
}
/// An enum to represent what operation to do on
pub enum KvOperation<'a, S: serde::Serialize + Debug> {
Hset((&'a str, String), TypedSql),
SetNx(&'a S, TypedSql),
HSetNx(&'a str, &'a S, TypedSql),
HGet(&'a str),
Get,
Scan(&'a str),
}
#[derive(TryGetEnumVariant)]
#[error(RedisError::UnknownResult)]
pub enum KvResult<T: de::DeserializeOwned> {
HGet(T),
Get(T),
Hset(()),
SetNx(redis_interface::SetnxReply),
HSetNx(redis_interface::HsetnxReply),
Scan(Vec<T>),
}
impl<T> std::fmt::Display for KvOperation<'_, T>
where
T: serde::Serialize + Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KvOperation::Hset(_, _) => f.write_str("Hset"),
KvOperation::SetNx(_, _) => f.write_str("Setnx"),
KvOperation::HSetNx(_, _, _) => f.write_str("HSetNx"),
KvOperation::HGet(_) => f.write_str("Hget"),
KvOperation::Get => f.write_str("Get"),
KvOperation::Scan(_) => f.write_str("Scan"),
}
}
}
pub async fn kv_wrapper<'a, T, D, S>(
store: &KVRouterStore<D>,
op: KvOperation<'a, S>,
partition_key: PartitionKey<'a>,
) -> CustomResult<KvResult<T>, RedisError>
where
T: de::DeserializeOwned,
D: crate::database::store::DatabaseStore,
S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync,
{
let redis_conn = store.get_redis_conn()?;
let key = format!("{}", partition_key);
let type_name = std::any::type_name::<T>();
let operation = op.to_string();
let ttl = store.ttl_for_kv;
let result = async {
match op {
KvOperation::Hset(value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
redis_conn
.set_hash_fields(&key.into(), value, Some(ttl.into()))
.await?;
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::Hset(()))
}
KvOperation::HGet(field) => {
let result = redis_conn
.get_hash_field_and_deserialize(&key.into(), field, type_name)
.await?;
Ok(KvResult::HGet(result))
}
KvOperation::Scan(pattern) => {
let result: Vec<T> = redis_conn
.hscan_and_deserialize(&key.into(), pattern, None)
.await
.and_then(|result| {
if result.is_empty() {
Err(report!(RedisError::NotFound))
} else {
Ok(result)
}
})?;
Ok(KvResult::Scan(result))
}
KvOperation::HSetNx(field, value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
value.check_for_constraints(&redis_conn).await?;
let result = redis_conn
.serialize_and_set_hash_field_if_not_exist(&key.into(), field, value, Some(ttl))
.await?;
if matches!(result, redis_interface::HsetnxReply::KeySet) {
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::HSetNx(result))
} else {
Err(report!(RedisError::SetNxFailed))
}
}
KvOperation::SetNx(value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
let result = redis_conn
.serialize_and_set_key_if_not_exist(&key.into(), value, Some(ttl.into()))
.await?;
value.check_for_constraints(&redis_conn).await?;
if matches!(result, redis_interface::SetnxReply::KeySet) {
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::SetNx(result))
} else {
Err(report!(RedisError::SetNxFailed))
}
}
KvOperation::Get => {
let result = redis_conn
.get_and_deserialize_key(&key.into(), type_name)
.await?;
Ok(KvResult::Get(result))
}
}
};
let attributes = router_env::metric_attributes!(("operation", operation.clone()));
result
.await
.inspect(|_| {
logger::debug!(kv_operation= %operation, status="success");
metrics::KV_OPERATION_SUCCESSFUL.add(1, attributes);
})
.inspect_err(|err| {
logger::error!(kv_operation = %operation, status="error", error = ?err);
metrics::KV_OPERATION_FAILED.add(1, attributes);
})
}
pub enum Op<'a> {
Insert,
Update(PartitionKey<'a>, &'a str, Option<&'a str>),
Find,
}
impl std::fmt::Display for Op<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Op::Insert => f.write_str("insert"),
Op::Find => f.write_str("find"),
Op::Update(p_key, _, updated_by) => {
f.write_str(&format!("update_{} for updated_by_{:?}", p_key, updated_by))
}
}
}
}
pub async fn decide_storage_scheme<T, D>(
store: &KVRouterStore<T>,
storage_scheme: MerchantStorageScheme,
operation: Op<'_>,
) -> MerchantStorageScheme
where
D: de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync,
T: crate::database::store::DatabaseStore,
{
if store.soft_kill_mode {
let ops = operation.to_string();
let updated_scheme = match operation {
Op::Insert => MerchantStorageScheme::PostgresOnly,
Op::Find => MerchantStorageScheme::RedisKv,
Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
Op::Update(partition_key, field, Some(_updated_by)) => {
match Box::pin(kv_wrapper::<D, _, _>(
store,
KvOperation::<D>::HGet(field),
partition_key,
))
.await
{
Ok(_) => {
metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(1, &[]);
MerchantStorageScheme::RedisKv
}
Err(_) => MerchantStorageScheme::PostgresOnly,
}
}
Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly,
};
let type_name = std::any::type_name::<D>();
logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops);
updated_scheme
} else {
storage_scheme
}
}
| 2,544 | 1,054 |
hyperswitch | crates/storage_impl/src/payouts/payout_attempt.rs | .rs | use std::str::FromStr;
use api_models::enums::PayoutConnectors;
use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found};
use diesel_models::{
enums::MerchantStorageScheme,
kv,
payout_attempt::{
PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew,
PayoutAttemptUpdate as DieselPayoutAttemptUpdate,
},
reverse_lookup::ReverseLookup,
ReverseLookupNew,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payouts::{
payout_attempt::{
PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,
PayoutListFilters,
},
payouts::Payouts,
};
use redis_interface::HsetnxReply;
use router_env::{instrument, logger, tracing};
use crate::{
diesel_error_to_data_error, errors,
errors::RedisErrorExt,
kv_router_store::KVRouterStore,
lookup::ReverseLookupInterface,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, pg_connection_read, pg_connection_write},
DataModelExt, DatabaseStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
type Error = errors::StorageError;
#[instrument(skip_all)]
async fn insert_payout_attempt(
&self,
new_payout_attempt: PayoutAttemptNew,
payouts: &Payouts,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payout_attempt(new_payout_attempt, payouts, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let merchant_id = new_payout_attempt.merchant_id.clone();
let payout_attempt_id = new_payout_attempt.payout_id.clone();
let key = PartitionKey::MerchantIdPayoutAttemptId {
merchant_id: &merchant_id,
payout_attempt_id: &payout_attempt_id,
};
let key_str = key.to_string();
let created_attempt = PayoutAttempt {
payout_attempt_id: new_payout_attempt.payout_attempt_id.clone(),
payout_id: new_payout_attempt.payout_id.clone(),
additional_payout_method_data: new_payout_attempt
.additional_payout_method_data
.clone(),
customer_id: new_payout_attempt.customer_id.clone(),
merchant_id: new_payout_attempt.merchant_id.clone(),
address_id: new_payout_attempt.address_id.clone(),
connector: new_payout_attempt.connector.clone(),
connector_payout_id: new_payout_attempt.connector_payout_id.clone(),
payout_token: new_payout_attempt.payout_token.clone(),
status: new_payout_attempt.status,
is_eligible: new_payout_attempt.is_eligible,
error_message: new_payout_attempt.error_message.clone(),
error_code: new_payout_attempt.error_code.clone(),
business_country: new_payout_attempt.business_country,
business_label: new_payout_attempt.business_label.clone(),
created_at: new_payout_attempt.created_at,
last_modified_at: new_payout_attempt.last_modified_at,
profile_id: new_payout_attempt.profile_id.clone(),
merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(),
routing_info: new_payout_attempt.routing_info.clone(),
unified_code: new_payout_attempt.unified_code.clone(),
unified_message: new_payout_attempt.unified_message.clone(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PayoutAttempt(
new_payout_attempt.to_storage_model(),
)),
},
};
// Reverse lookup for payout_attempt_id
let field = format!("poa_{}", created_attempt.payout_attempt_id);
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
"poa_{}_{}",
&created_attempt.merchant_id.get_string_repr(),
&created_attempt.payout_attempt_id,
),
pk_id: key_str.clone(),
sk_id: field.clone(),
source: "payout_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>(
self,
KvOperation::<DieselPayoutAttempt>::HSetNx(
&field,
&created_attempt.clone().to_storage_model(),
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "payout attempt",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_attempt),
Err(error) => Err(error.change_context(errors::StorageError::KVError)),
}
}
}
}
#[instrument(skip_all)]
async fn update_payout_attempt(
&self,
this: &PayoutAttempt,
payout_update: PayoutAttemptUpdate,
payouts: &Payouts,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let key = PartitionKey::MerchantIdPayoutAttemptId {
merchant_id: &this.merchant_id,
payout_attempt_id: &this.payout_id,
};
let field = format!("poa_{}", this.payout_attempt_id);
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Update(key.clone(), &field, None),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payout_attempt(this, payout_update, payouts, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let diesel_payout_update = payout_update.clone().to_storage_model();
let origin_diesel_payout = this.clone().to_storage_model();
let diesel_payout = diesel_payout_update
.clone()
.apply_changeset(origin_diesel_payout.clone());
// Check for database presence as well Maybe use a read replica here ?
let redis_value = diesel_payout
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PayoutAttemptUpdate(
kv::PayoutAttemptUpdateMems {
orig: origin_diesel_payout,
update_data: diesel_payout_update,
},
)),
},
};
let updated_attempt = PayoutAttempt::from_storage_model(
payout_update
.to_storage_model()
.apply_changeset(this.clone().to_storage_model()),
);
let old_connector_payout_id = this.connector_payout_id.clone();
match (
old_connector_payout_id,
updated_attempt.connector_payout_id.clone(),
) {
(Some(old), Some(new)) if old != new => {
add_connector_payout_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.payout_attempt_id.as_str(),
new.as_str(),
storage_scheme,
)
.await?;
}
(None, Some(new)) => {
add_connector_payout_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.payout_attempt_id.as_str(),
new.as_str(),
storage_scheme,
)
.await?;
}
_ => {}
}
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(errors::StorageError::KVError)?;
Ok(PayoutAttempt::from_storage_model(diesel_payout))
}
}
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id =
format!("poa_{}_{payout_attempt_id}", merchant_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"po_conn_payout_{}_{connector_payout_id}",
merchant_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[instrument(skip_all)]
async fn get_filters_for_payouts(
&self,
payouts: &[Payouts],
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, errors::StorageError> {
self.router_store
.get_filters_for_payouts(payouts, merchant_id, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
type Error = errors::StorageError;
#[instrument(skip_all)]
async fn insert_payout_attempt(
&self,
new: PayoutAttemptNew,
_payouts: &Payouts,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
new.to_storage_model()
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PayoutAttempt::from_storage_model)
}
#[instrument(skip_all)]
async fn update_payout_attempt(
&self,
this: &PayoutAttempt,
payout: PayoutAttemptUpdate,
_payouts: &Payouts,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
this.clone()
.to_storage_model()
.update_with_attempt_id(&conn, payout.to_storage_model())
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PayoutAttempt::from_storage_model)
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayoutAttempt::find_by_merchant_id_payout_attempt_id(
&conn,
merchant_id,
payout_attempt_id,
)
.await
.map(PayoutAttempt::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayoutAttempt::find_by_merchant_id_connector_payout_id(
&conn,
merchant_id,
connector_payout_id,
)
.await
.map(PayoutAttempt::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn get_filters_for_payouts(
&self,
payouts: &[Payouts],
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PayoutListFilters, errors::StorageError> {
let conn = pg_connection_read(self).await?;
let payouts = payouts
.iter()
.cloned()
.map(|payouts| payouts.to_storage_model())
.collect::<Vec<diesel_models::Payouts>>();
DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(
|(connector, currency, status, payout_method)| PayoutListFilters {
connector: connector
.iter()
.filter_map(|c| {
PayoutConnectors::from_str(c)
.map_err(|e| {
logger::error!(
"Failed to parse payout connector '{}' - {}",
c,
e
);
})
.ok()
})
.collect(),
currency,
status,
payout_method,
},
)
}
}
impl DataModelExt for PayoutAttempt {
type StorageModel = DieselPayoutAttempt;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayoutAttempt {
payout_attempt_id: self.payout_attempt_id,
payout_id: self.payout_id,
customer_id: self.customer_id,
merchant_id: self.merchant_id,
address_id: self.address_id,
connector: self.connector,
connector_payout_id: self.connector_payout_id,
payout_token: self.payout_token,
status: self.status,
is_eligible: self.is_eligible,
error_message: self.error_message,
error_code: self.error_code,
business_country: self.business_country,
business_label: self.business_label,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
routing_info: self.routing_info,
unified_code: self.unified_code,
unified_message: self.unified_message,
additional_payout_method_data: self.additional_payout_method_data,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_attempt_id: storage_model.payout_attempt_id,
payout_id: storage_model.payout_id,
customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
address_id: storage_model.address_id,
connector: storage_model.connector,
connector_payout_id: storage_model.connector_payout_id,
payout_token: storage_model.payout_token,
status: storage_model.status,
is_eligible: storage_model.is_eligible,
error_message: storage_model.error_message,
error_code: storage_model.error_code,
business_country: storage_model.business_country,
business_label: storage_model.business_label,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
merchant_connector_id: storage_model.merchant_connector_id,
routing_info: storage_model.routing_info,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
additional_payout_method_data: storage_model.additional_payout_method_data,
}
}
}
impl DataModelExt for PayoutAttemptNew {
type StorageModel = DieselPayoutAttemptNew;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayoutAttemptNew {
payout_attempt_id: self.payout_attempt_id,
payout_id: self.payout_id,
customer_id: self.customer_id,
merchant_id: self.merchant_id,
address_id: self.address_id,
connector: self.connector,
connector_payout_id: self.connector_payout_id,
payout_token: self.payout_token,
status: self.status,
is_eligible: self.is_eligible,
error_message: self.error_message,
error_code: self.error_code,
business_country: self.business_country,
business_label: self.business_label,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
routing_info: self.routing_info,
unified_code: self.unified_code,
unified_message: self.unified_message,
additional_payout_method_data: self.additional_payout_method_data,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_attempt_id: storage_model.payout_attempt_id,
payout_id: storage_model.payout_id,
customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
address_id: storage_model.address_id,
connector: storage_model.connector,
connector_payout_id: storage_model.connector_payout_id,
payout_token: storage_model.payout_token,
status: storage_model.status,
is_eligible: storage_model.is_eligible,
error_message: storage_model.error_message,
error_code: storage_model.error_code,
business_country: storage_model.business_country,
business_label: storage_model.business_label,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
merchant_connector_id: storage_model.merchant_connector_id,
routing_info: storage_model.routing_info,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
additional_payout_method_data: storage_model.additional_payout_method_data,
}
}
}
impl DataModelExt for PayoutAttemptUpdate {
type StorageModel = DieselPayoutAttemptUpdate;
fn to_storage_model(self) -> Self::StorageModel {
match self {
Self::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
} => DieselPayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
},
Self::PayoutTokenUpdate { payout_token } => {
DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token }
}
Self::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
} => DieselPayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
},
Self::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
} => DieselPayoutAttemptUpdate::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
},
Self::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
} => DieselPayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
},
}
}
#[allow(clippy::todo)]
fn from_storage_model(_storage_model: Self::StorageModel) -> Self {
todo!("Reverse map should no longer be needed")
}
}
#[inline]
#[instrument(skip_all)]
async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("poa_{}", updated_attempt_attempt_id);
let reverse_lookup_new = ReverseLookupNew {
lookup_id: format!(
"po_conn_payout_{}_{}",
merchant_id.get_string_repr(),
connector_payout_id
),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payout_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
store
.insert_reverse_lookup(reverse_lookup_new, storage_scheme)
.await
}
| 5,213 | 1,055 |
hyperswitch | crates/storage_impl/src/payouts/payouts.rs | .rs | #[cfg(feature = "olap")]
use api_models::enums::PayoutConnectors;
#[cfg(feature = "olap")]
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::ext_traits::Encode;
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
use diesel::JoinOnDsl;
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, NullableExpressionMethods, QueryDsl};
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
use diesel_models::payout_attempt::PayoutAttempt as DieselPayoutAttempt;
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
use diesel_models::schema::{
address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl,
};
#[cfg(feature = "olap")]
use diesel_models::{
address::Address as DieselAddress, customers::Customer as DieselCustomer,
enums as storage_enums, query::generics::db_metrics, schema::payouts::dsl as po_dsl,
};
use diesel_models::{
enums::MerchantStorageScheme,
kv,
payouts::{
Payouts as DieselPayouts, PayoutsNew as DieselPayoutsNew,
PayoutsUpdate as DieselPayoutsUpdate,
},
};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payouts::PayoutFetchConstraints;
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttempt,
payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},
};
use redis_interface::HsetnxReply;
#[cfg(feature = "olap")]
use router_env::logger;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use crate::connection;
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
use crate::store::schema::{
address::all_columns as addr_all_columns, customers::all_columns as cust_all_columns,
payout_attempt::all_columns as poa_all_columns, payouts::all_columns as po_all_columns,
};
use crate::{
diesel_error_to_data_error,
errors::{RedisErrorExt, StorageError},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, pg_connection_read, pg_connection_write},
DataModelExt, DatabaseStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_payout(
&self,
new: PayoutsNew,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store.insert_payout(new, storage_scheme).await
}
MerchantStorageScheme::RedisKv => {
let merchant_id = new.merchant_id.clone();
let payout_id = new.payout_id.clone();
let key = PartitionKey::MerchantIdPayoutId {
merchant_id: &merchant_id,
payout_id: &payout_id,
};
let key_str = key.to_string();
let field = format!("po_{}", new.payout_id);
let created_payout = Payouts {
payout_id: new.payout_id.clone(),
merchant_id: new.merchant_id.clone(),
customer_id: new.customer_id.clone(),
address_id: new.address_id.clone(),
payout_type: new.payout_type,
payout_method_id: new.payout_method_id.clone(),
amount: new.amount,
destination_currency: new.destination_currency,
source_currency: new.source_currency,
description: new.description.clone(),
recurring: new.recurring,
auto_fulfill: new.auto_fulfill,
return_url: new.return_url.clone(),
entity_type: new.entity_type,
metadata: new.metadata.clone(),
created_at: new.created_at,
last_modified_at: new.last_modified_at,
profile_id: new.profile_id.clone(),
status: new.status,
attempt_count: new.attempt_count,
confirm: new.confirm,
payout_link_id: new.payout_link_id.clone(),
client_secret: new.client_secret.clone(),
priority: new.priority,
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())),
},
};
match Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HSetNx(
&field,
&created_payout.clone().to_storage_model(),
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue {
entity: "payouts",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_payout),
Err(error) => Err(error.change_context(StorageError::KVError)),
}
}
}
}
#[instrument(skip_all)]
async fn update_payout(
&self,
this: &Payouts,
payout_update: PayoutsUpdate,
payout_attempt: &PayoutAttempt,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let key = PartitionKey::MerchantIdPayoutId {
merchant_id: &this.merchant_id,
payout_id: &this.payout_id,
};
let field = format!("po_{}", this.payout_id);
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Update(key.clone(), &field, None),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payout(this, payout_update, payout_attempt, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let diesel_payout_update = payout_update.to_storage_model();
let origin_diesel_payout = this.clone().to_storage_model();
let diesel_payout = diesel_payout_update
.clone()
.apply_changeset(origin_diesel_payout.clone());
// Check for database presence as well Maybe use a read replica here ?
let redis_value = diesel_payout
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems {
orig: origin_diesel_payout,
update_data: diesel_payout_update,
})),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(StorageError::KVError)?;
Ok(Payouts::from_storage_model(diesel_payout))
}
}
}
#[instrument(skip_all)]
async fn find_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
};
let field = format!("po_{payout_id}");
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
.map(Payouts::from_storage_model)
}
#[instrument(skip_all)]
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, StorageError> {
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let maybe_payouts = database_call().await?;
Ok(maybe_payouts.and_then(|payout| {
if payout.payout_id == payout_id {
Some(payout)
} else {
None
}
}))
}
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
};
let field = format!("po_{payout_id}");
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HGet(&field),
key,
))
.await?
.try_into_hget()
.map(Some)
},
database_call,
))
.await
}
}
.map(|payout| payout.map(Payouts::from_storage_model))
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
self.router_store
.filter_payouts_by_constraints(merchant_id, filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>,
StorageError,
> {
self.router_store
.filter_payouts_and_attempts(merchant_id, filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
#[instrument[skip_all]]
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
self.router_store
.filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)
.await
}
#[cfg(feature = "olap")]
async fn get_total_count_of_filtered_payouts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_payout_ids: &[String],
connector: Option<Vec<PayoutConnectors>>,
currency: Option<Vec<storage_enums::Currency>>,
status: Option<Vec<storage_enums::PayoutStatus>>,
payout_method: Option<Vec<storage_enums::PayoutType>>,
) -> error_stack::Result<i64, StorageError> {
self.router_store
.get_total_count_of_filtered_payouts(
merchant_id,
active_payout_ids,
connector,
currency,
status,
payout_method,
)
.await
}
#[cfg(feature = "olap")]
async fn filter_active_payout_ids_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<String>, StorageError> {
self.router_store
.filter_active_payout_ids_by_constraints(merchant_id, constraints)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_payout(
&self,
new: PayoutsNew,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let conn = pg_connection_write(self).await?;
new.to_storage_model()
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(Payouts::from_storage_model)
}
#[instrument(skip_all)]
async fn update_payout(
&self,
this: &Payouts,
payout: PayoutsUpdate,
_payout_attempt: &PayoutAttempt,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let conn = pg_connection_write(self).await?;
this.clone()
.to_storage_model()
.update(&conn, payout.to_storage_model())
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(Payouts::from_storage_model)
}
#[instrument(skip_all)]
async fn find_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map(Payouts::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map(|x| x.map(Payouts::from_storage_model))
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
let mut query = <DieselPayouts as HasTable>::table()
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
.into_boxed();
match filters {
PayoutFetchConstraints::Single { payout_id } => {
query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned()));
}
PayoutFetchConstraints::List(params) => {
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
starting_after_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
ending_before_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
if let Some(currency) = ¶ms.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
if let Some(status) = ¶ms.status {
query = query.filter(po_dsl::status.eq_any(status.clone()));
}
}
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
query.get_results_async::<DieselPayouts>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map(|payouts| {
payouts
.into_iter()
.map(Payouts::from_storage_model)
.collect::<Vec<Payouts>>()
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payout records"),
)
.into()
})
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
feature = "olap",
not(feature = "customer_v2")
))]
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>,
StorageError,
> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPayouts::table()
.inner_join(
diesel_models::schema::payout_attempt::table
.on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
)
.left_join(
diesel_models::schema::customers::table
.on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
)
.filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
.left_outer_join(
diesel_models::schema::address::table
.on(add_dsl::address_id.nullable().eq(po_dsl::address_id)),
)
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
.into_boxed();
query = match filters {
PayoutFetchConstraints::Single { payout_id } => {
query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))
}
PayoutFetchConstraints::List(params) => {
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
starting_after_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
ending_before_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
if let Some(currency) = ¶ms.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
let connectors = params
.connector
.as_ref()
.map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>());
query = match connectors {
Some(connectors) => query.filter(poa_dsl::connector.eq_any(connectors)),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),
None => query,
};
query = match ¶ms.payout_method {
Some(payout_method) => {
query.filter(po_dsl::payout_type.eq_any(payout_method.clone()))
}
None => query,
};
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.select((
po_all_columns,
poa_all_columns,
cust_all_columns.nullable(),
addr_all_columns.nullable(),
))
.get_results_async::<(
DieselPayouts,
DieselPayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>(conn)
.await
.map(|results| {
results
.into_iter()
.map(|(pi, pa, c, add)| {
(
Payouts::from_storage_model(pi),
PayoutAttempt::from_storage_model(pa),
c,
add,
)
})
.collect()
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payout records"),
)
.into()
})
}
#[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))]
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>,
StorageError,
> {
todo!()
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let payout_filters = (*time_range).into();
self.filter_payouts_by_constraints(merchant_id, &payout_filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payouts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_payout_ids: &[String],
connector: Option<Vec<PayoutConnectors>>,
currency: Option<Vec<storage_enums::Currency>>,
status: Option<Vec<storage_enums::PayoutStatus>>,
payout_type: Option<Vec<storage_enums::PayoutType>>,
) -> error_stack::Result<i64, StorageError> {
let conn = self
.db_store
.get_replica_pool()
.get()
.await
.change_context(StorageError::DatabaseConnectionError)?;
let connector_strings = connector.as_ref().map(|connectors| {
connectors
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
});
DieselPayouts::get_total_count_of_payouts(
&conn,
merchant_id,
active_payout_ids,
connector_strings,
currency,
status,
payout_type,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
feature = "olap",
not(feature = "customer_v2")
))]
#[instrument(skip_all)]
async fn filter_active_payout_ids_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<String>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPayouts::table()
.inner_join(
diesel_models::schema::payout_attempt::table
.on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
)
.left_join(
diesel_models::schema::customers::table
.on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
)
.select(po_dsl::payout_id)
.filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
.into_boxed();
query = match constraints {
PayoutFetchConstraints::Single { payout_id } => {
query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))
}
PayoutFetchConstraints::List(params) => {
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
}
query = match params.starting_at {
Some(starting_at) => query.filter(po_dsl::created_at.ge(starting_at)),
None => query,
};
query = match params.ending_at {
Some(ending_at) => query.filter(po_dsl::created_at.le(ending_at)),
None => query,
};
query = match ¶ms.currency {
Some(currency) => {
query.filter(po_dsl::destination_currency.eq_any(currency.clone()))
}
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),
None => query,
};
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
query.get_results_async::<String>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payout records"),
)
.into()
})
}
#[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))]
#[instrument(skip_all)]
async fn filter_active_payout_ids_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<String>, StorageError> {
todo!()
}
}
impl DataModelExt for Payouts {
type StorageModel = DieselPayouts;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayouts {
payout_id: self.payout_id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
address_id: self.address_id,
payout_type: self.payout_type,
payout_method_id: self.payout_method_id,
amount: self.amount,
destination_currency: self.destination_currency,
source_currency: self.source_currency,
description: self.description,
recurring: self.recurring,
auto_fulfill: self.auto_fulfill,
return_url: self.return_url,
entity_type: self.entity_type,
metadata: self.metadata,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
status: self.status,
attempt_count: self.attempt_count,
confirm: self.confirm,
payout_link_id: self.payout_link_id,
client_secret: self.client_secret,
priority: self.priority,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_id: storage_model.payout_id,
merchant_id: storage_model.merchant_id,
customer_id: storage_model.customer_id,
address_id: storage_model.address_id,
payout_type: storage_model.payout_type,
payout_method_id: storage_model.payout_method_id,
amount: storage_model.amount,
destination_currency: storage_model.destination_currency,
source_currency: storage_model.source_currency,
description: storage_model.description,
recurring: storage_model.recurring,
auto_fulfill: storage_model.auto_fulfill,
return_url: storage_model.return_url,
entity_type: storage_model.entity_type,
metadata: storage_model.metadata,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
status: storage_model.status,
attempt_count: storage_model.attempt_count,
confirm: storage_model.confirm,
payout_link_id: storage_model.payout_link_id,
client_secret: storage_model.client_secret,
priority: storage_model.priority,
}
}
}
impl DataModelExt for PayoutsNew {
type StorageModel = DieselPayoutsNew;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayoutsNew {
payout_id: self.payout_id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
address_id: self.address_id,
payout_type: self.payout_type,
payout_method_id: self.payout_method_id,
amount: self.amount,
destination_currency: self.destination_currency,
source_currency: self.source_currency,
description: self.description,
recurring: self.recurring,
auto_fulfill: self.auto_fulfill,
return_url: self.return_url,
entity_type: self.entity_type,
metadata: self.metadata,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
status: self.status,
attempt_count: self.attempt_count,
confirm: self.confirm,
payout_link_id: self.payout_link_id,
client_secret: self.client_secret,
priority: self.priority,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_id: storage_model.payout_id,
merchant_id: storage_model.merchant_id,
customer_id: storage_model.customer_id,
address_id: storage_model.address_id,
payout_type: storage_model.payout_type,
payout_method_id: storage_model.payout_method_id,
amount: storage_model.amount,
destination_currency: storage_model.destination_currency,
source_currency: storage_model.source_currency,
description: storage_model.description,
recurring: storage_model.recurring,
auto_fulfill: storage_model.auto_fulfill,
return_url: storage_model.return_url,
entity_type: storage_model.entity_type,
metadata: storage_model.metadata,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
status: storage_model.status,
attempt_count: storage_model.attempt_count,
confirm: storage_model.confirm,
payout_link_id: storage_model.payout_link_id,
client_secret: storage_model.client_secret,
priority: storage_model.priority,
}
}
}
impl DataModelExt for PayoutsUpdate {
type StorageModel = DieselPayoutsUpdate;
fn to_storage_model(self) -> Self::StorageModel {
match self {
Self::Update {
amount,
destination_currency,
source_currency,
description,
recurring,
auto_fulfill,
return_url,
entity_type,
metadata,
profile_id,
status,
confirm,
payout_type,
address_id,
customer_id,
} => DieselPayoutsUpdate::Update {
amount,
destination_currency,
source_currency,
description,
recurring,
auto_fulfill,
return_url,
entity_type,
metadata,
profile_id,
status,
confirm,
payout_type,
address_id,
customer_id,
},
Self::PayoutMethodIdUpdate { payout_method_id } => {
DieselPayoutsUpdate::PayoutMethodIdUpdate { payout_method_id }
}
Self::RecurringUpdate { recurring } => {
DieselPayoutsUpdate::RecurringUpdate { recurring }
}
Self::AttemptCountUpdate { attempt_count } => {
DieselPayoutsUpdate::AttemptCountUpdate { attempt_count }
}
Self::StatusUpdate { status } => DieselPayoutsUpdate::StatusUpdate { status },
}
}
#[allow(clippy::todo)]
fn from_storage_model(_storage_model: Self::StorageModel) -> Self {
todo!("Reverse map should no longer be needed")
}
}
| 8,315 | 1,056 |
hyperswitch | crates/router_env/Cargo.toml | .toml | [package]
name = "router_env"
description = "Environment of payment router: logger, basic config, its environment awareness."
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[dependencies]
cargo_metadata = "0.18.1"
config = { version = "0.14.0", features = ["toml"] }
error-stack = "0.4.1"
gethostname = "0.4.3"
once_cell = "1.19.0"
opentelemetry = { version = "0.27.1", default-features = false, features = ["internal-logs", "metrics", "trace"] }
opentelemetry-aws = { version = "0.15.0", default-features = false, features = ["internal-logs", "trace"] }
opentelemetry-otlp = { version = "0.27.0", default-features = false, features = ["grpc-tonic", "metrics", "trace"] }
opentelemetry_sdk = { version = "0.27.1", default-features = false, features = ["rt-tokio-current-thread", "metrics", "trace"] }
rustc-hash = "1.1"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
serde_path_to_error = "0.1.16"
strum = { version = "0.26.2", features = ["derive"] }
time = { version = "0.3.35", default-features = false, features = ["formatting"] }
tokio = { version = "1.37.0" }
tracing = { workspace = true }
tracing-actix-web = { version = "0.7.15", features = ["opentelemetry_0_27", "uuid_v7"], optional = true }
tracing-appender = { version = "0.2.3" }
tracing-attributes = "0.1.27"
tracing-opentelemetry = { version = "0.28.0", default-features = false }
tracing-subscriber = { version = "0.3.18", default-features = true, features = ["env-filter", "json", "registry"] }
vergen = { version = "8.3.1", optional = true, features = ["cargo", "git", "git2", "rustc"] }
[dev-dependencies]
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
cargo_metadata = "0.18.1"
vergen = { version = "8.3.1", features = ["cargo", "git", "git2", "rustc"], optional = true }
[features]
default = ["actix_web", "payouts"]
actix_web = ["tracing-actix-web"]
log_custom_entries_to_extra = []
log_extra_implicit_fields = []
log_active_span_json = []
payouts = []
[lints]
workspace = true
| 691 | 1,057 |
hyperswitch | crates/router_env/build.rs | .rs | mod vergen {
include!("src/vergen.rs");
}
mod cargo_workspace {
include!("src/cargo_workspace.rs");
}
fn main() {
vergen::generate_cargo_instructions();
cargo_workspace::verify_cargo_metadata_format();
cargo_workspace::set_cargo_workspace_members_env();
}
| 63 | 1,058 |
hyperswitch | crates/router_env/README.md | .md | # router_env
Environment of payment router: logger, basic config, its environment awareness.
## Example
```rust
use router_env::logger;
use tracing::{self, instrument};
#[instrument]
pub fn sample() -> () {
logger::log!(
logger::Level::INFO,
payment_id = 8565654,
payment_attempt_id = 596456465,
merchant_id = 954865,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
);
}
```
| 142 | 1,059 |
hyperswitch | crates/router_env/tests/test_module.rs | .rs | use router_env as logger;
#[tracing::instrument(skip_all)]
pub async fn fn_with_colon(val: i32) {
let a = 13;
let b = 31;
logger::log!(
logger::Level::WARN,
?a,
?b,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
answer = 13,
message2 = "yyy",
message = "Experiment",
val,
);
fn_without_colon(131).await;
}
#[tracing::instrument(fields(val3 = "abc"), skip_all)]
pub async fn fn_without_colon(val: i32) {
let a = 13;
let b = 31;
// trace_macros!(true);
logger::log!(
logger::Level::INFO,
?a,
?b,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
answer = 13,
message2 = "yyy",
message = "Experiment",
val,
);
// trace_macros!(false);
}
| 281 | 1,060 |
hyperswitch | crates/router_env/tests/env.rs | .rs | #![allow(clippy::print_stdout)]
#[cfg(feature = "vergen")]
use router_env as env;
#[cfg(feature = "vergen")]
#[tokio::test]
async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("CARGO_PKG_VERSION : {:?}", env!("CARGO_PKG_VERSION"));
println!("CARGO_PROFILE : {:?}", env!("CARGO_PROFILE"));
println!(
"GIT_COMMIT_TIMESTAMP : {:?}",
env!("VERGEN_GIT_COMMIT_TIMESTAMP")
);
println!("GIT_SHA : {:?}", env!("VERGEN_GIT_SHA"));
println!("RUSTC_SEMVER : {:?}", env!("VERGEN_RUSTC_SEMVER"));
println!(
"CARGO_TARGET_TRIPLE : {:?}",
env!("VERGEN_CARGO_TARGET_TRIPLE")
);
Ok(())
}
#[cfg(feature = "vergen")]
#[tokio::test]
async fn env_macro() {
println!("version : {:?}", env::version!());
println!("build : {:?}", env::build!());
println!("commit : {:?}", env::commit!());
// println!("platform : {:?}", env::platform!());
assert!(!env::version!().is_empty());
assert!(!env::build!().is_empty());
assert!(!env::commit!().is_empty());
// assert!(env::platform!().len() > 0);
}
| 301 | 1,061 |
hyperswitch | crates/router_env/tests/logger.rs | .rs | #![allow(clippy::unwrap_used)]
mod test_module;
use ::config::ConfigError;
use router_env::TelemetryGuard;
use self::test_module::fn_with_colon;
fn logger() -> error_stack::Result<&'static TelemetryGuard, ConfigError> {
use once_cell::sync::OnceCell;
static INSTANCE: OnceCell<TelemetryGuard> = OnceCell::new();
Ok(INSTANCE.get_or_init(|| {
let config = router_env::Config::new().unwrap();
router_env::setup(&config.log, "router_env_test", []).unwrap()
}))
}
#[tokio::test]
async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
logger()?;
fn_with_colon(13).await;
Ok(())
}
| 171 | 1,062 |
hyperswitch | crates/router_env/src/metrics.rs | .rs | //! Utilities to easily create opentelemetry contexts, meters and metrics.
/// Create a global [`Meter`][Meter] with the specified name and an optional description.
///
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! global_meter {
($name:ident) => {
static $name: once_cell::sync::Lazy<$crate::opentelemetry::metrics::Meter> =
once_cell::sync::Lazy::new(|| $crate::opentelemetry::global::meter(stringify!($name)));
};
($meter:ident, $name:literal) => {
static $meter: once_cell::sync::Lazy<$crate::opentelemetry::metrics::Meter> =
once_cell::sync::Lazy::new(|| $crate::opentelemetry::global::meter(stringify!($name)));
};
}
/// Create a [`Counter`][Counter] metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Counter]: opentelemetry::metrics::Counter
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! counter_metric {
($name:ident, $meter:ident) => {
pub(crate) static $name: once_cell::sync::Lazy<
$crate::opentelemetry::metrics::Counter<u64>,
> = once_cell::sync::Lazy::new(|| $meter.u64_counter(stringify!($name)).build());
};
($name:ident, $meter:ident, description:literal) => {
#[doc = $description]
pub(crate) static $name: once_cell::sync::Lazy<
$crate::opentelemetry::metrics::Counter<u64>,
> = once_cell::sync::Lazy::new(|| {
$meter
.u64_counter(stringify!($name))
.with_description($description)
.build()
});
};
}
/// Create a [`Histogram`][Histogram] f64 metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Histogram]: opentelemetry::metrics::Histogram
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! histogram_metric_f64 {
($name:ident, $meter:ident) => {
pub(crate) static $name: once_cell::sync::Lazy<
$crate::opentelemetry::metrics::Histogram<f64>,
> = once_cell::sync::Lazy::new(|| {
$meter
.f64_histogram(stringify!($name))
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
($name:ident, $meter:ident, $description:literal) => {
#[doc = $description]
pub(crate) static $name: once_cell::sync::Lazy<
$crate::opentelemetry::metrics::Histogram<f64>,
> = once_cell::sync::Lazy::new(|| {
$meter
.f64_histogram(stringify!($name))
.with_description($description)
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
}
/// Create a [`Histogram`][Histogram] u64 metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Histogram]: opentelemetry::metrics::Histogram
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! histogram_metric_u64 {
($name:ident, $meter:ident) => {
pub(crate) static $name: once_cell::sync::Lazy<
$crate::opentelemetry::metrics::Histogram<u64>,
> = once_cell::sync::Lazy::new(|| {
$meter
.u64_histogram(stringify!($name))
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
($name:ident, $meter:ident, $description:literal) => {
#[doc = $description]
pub(crate) static $name: once_cell::sync::Lazy<
$crate::opentelemetry::metrics::Histogram<u64>,
> = once_cell::sync::Lazy::new(|| {
$meter
.u64_histogram(stringify!($name))
.with_description($description)
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
}
/// Create a [`Gauge`][Gauge] metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Gauge]: opentelemetry::metrics::Gauge
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! gauge_metric {
($name:ident, $meter:ident) => {
pub(crate) static $name: once_cell::sync::Lazy<$crate::opentelemetry::metrics::Gauge<u64>> =
once_cell::sync::Lazy::new(|| $meter.u64_gauge(stringify!($name)).build());
};
($name:ident, $meter:ident, description:literal) => {
#[doc = $description]
pub(crate) static $name: once_cell::sync::Lazy<$crate::opentelemetry::metrics::Gauge<u64>> =
once_cell::sync::Lazy::new(|| {
$meter
.u64_gauge(stringify!($name))
.with_description($description)
.build()
});
};
}
/// Create attributes to associate with a metric from key-value pairs.
#[macro_export]
macro_rules! metric_attributes {
($(($key:expr, $value:expr $(,)?)),+ $(,)?) => {
&[$($crate::opentelemetry::KeyValue::new($key, $value)),+]
};
}
pub use helpers::f64_histogram_buckets;
mod helpers {
/// Returns the buckets to be used for a f64 histogram
#[inline(always)]
pub fn f64_histogram_buckets() -> Vec<f64> {
let mut init = 0.01;
let mut buckets: [f64; 15] = [0.0; 15];
for bucket in &mut buckets {
init *= 2.0;
*bucket = init;
}
Vec::from(buckets)
}
}
| 1,442 | 1,063 |
hyperswitch | crates/router_env/src/cargo_workspace.rs | .rs | /// Sets the `CARGO_WORKSPACE_MEMBERS` environment variable to include a comma-separated list of
/// names of all crates in the current cargo workspace.
///
/// This function should be typically called within build scripts, so that the environment variable
/// is available to the corresponding crate at compile time.
///
/// # Panics
///
/// Panics if running the `cargo metadata` command fails.
#[allow(clippy::expect_used)]
pub fn set_cargo_workspace_members_env() {
use std::io::Write;
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.expect("Failed to obtain cargo metadata");
let workspace_members = metadata
.workspace_packages()
.iter()
.map(|package| package.name.as_str())
.collect::<Vec<_>>()
.join(",");
writeln!(
&mut std::io::stdout(),
"cargo:rustc-env=CARGO_WORKSPACE_MEMBERS={workspace_members}"
)
.expect("Failed to set `CARGO_WORKSPACE_MEMBERS` environment variable");
}
/// Verify that the cargo metadata workspace packages format matches that expected by
/// [`set_cargo_workspace_members_env`] to set the `CARGO_WORKSPACE_MEMBERS` environment variable.
///
/// This function should be typically called within build scripts, before the
/// [`set_cargo_workspace_members_env`] function is called.
///
/// # Panics
///
/// Panics if running the `cargo metadata` command fails, or if the workspace member package names
/// cannot be determined.
pub fn verify_cargo_metadata_format() {
#[allow(clippy::expect_used)]
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.expect("Failed to obtain cargo metadata");
assert!(
metadata
.workspace_packages()
.iter()
.any(|package| package.name == env!("CARGO_PKG_NAME")),
"Unable to determine workspace member package names from `cargo metadata`"
);
}
/// Obtain the crates in the current cargo workspace as a `HashSet`.
///
/// This macro requires that [`set_cargo_workspace_members_env()`] function be called in the
/// build script of the crate where this macro is being called.
///
/// # Errors
///
/// Causes a compilation error if the `CARGO_WORKSPACE_MEMBERS` environment variable is unset.
#[macro_export]
macro_rules! cargo_workspace_members {
() => {
std::env!("CARGO_WORKSPACE_MEMBERS")
.split(',')
.collect::<std::collections::HashSet<&'static str>>()
};
}
| 538 | 1,064 |
hyperswitch | crates/router_env/src/vergen.rs | .rs | /// Configures the [`vergen`][::vergen] crate to generate the `cargo` build instructions.
///
/// This function should be typically called within build scripts to generate `cargo` build
/// instructions for the corresponding crate.
///
/// # Panics
///
/// Panics if `vergen` fails to generate `cargo` build instructions.
#[cfg(feature = "vergen")]
#[allow(clippy::expect_used)]
pub fn generate_cargo_instructions() {
use std::io::Write;
use vergen::EmitBuilder;
EmitBuilder::builder()
.cargo_debug()
.cargo_opt_level()
.cargo_target_triple()
.git_commit_timestamp()
.git_describe(true, true, None)
.git_sha(true)
.rustc_semver()
.rustc_commit_hash()
.emit()
.expect("Failed to generate `cargo` build instructions");
writeln!(
&mut std::io::stdout(),
"cargo:rustc-env=CARGO_PROFILE={}",
std::env::var("PROFILE").expect("Failed to obtain `cargo` profile")
)
.expect("Failed to set `CARGO_PROFILE` environment variable");
}
#[cfg(not(feature = "vergen"))]
pub fn generate_cargo_instructions() {}
| 272 | 1,065 |
hyperswitch | crates/router_env/src/env.rs | .rs | //! Information about the current environment.
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// Environment variables accessed by the application. This module aims to be the source of truth
/// containing all environment variable that the application accesses.
pub mod vars {
/// Parent directory where `Cargo.toml` is stored.
pub const CARGO_MANIFEST_DIR: &str = "CARGO_MANIFEST_DIR";
/// Environment variable that sets development/sandbox/production environment.
pub const RUN_ENV: &str = "RUN_ENV";
/// Directory of config TOML files. Default is `config`.
pub const CONFIG_DIR: &str = "CONFIG_DIR";
}
/// Current environment.
#[derive(
Debug, Default, Deserialize, Serialize, Clone, Copy, strum::Display, strum::EnumString,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Env {
/// Development environment.
#[default]
Development,
/// Sandbox environment.
Sandbox,
/// Production environment.
Production,
}
/// Name of current environment. Either "development", "sandbox" or "production".
pub fn which() -> Env {
#[cfg(debug_assertions)]
let default_env = Env::Development;
#[cfg(not(debug_assertions))]
let default_env = Env::Production;
std::env::var(vars::RUN_ENV).map_or_else(|_| default_env, |v| v.parse().unwrap_or(default_env))
}
/// Three letter (lowercase) prefix corresponding to the current environment.
/// Either `dev`, `snd` or `prd`.
pub fn prefix_for_env() -> &'static str {
match which() {
Env::Development => "dev",
Env::Sandbox => "snd",
Env::Production => "prd",
}
}
/// Path to the root directory of the cargo workspace.
/// It is recommended that this be used by the application as the base path to build other paths
/// such as configuration and logs directories.
pub fn workspace_path() -> PathBuf {
if let Ok(manifest_dir) = std::env::var(vars::CARGO_MANIFEST_DIR) {
let mut path = PathBuf::from(manifest_dir);
path.pop();
path.pop();
path
} else {
PathBuf::from(".")
}
}
/// Version of the crate containing the following information:
///
/// - The latest git tag. If tags are not present in the repository, the short commit hash is used
/// instead.
/// - Short hash of the latest git commit.
/// - Timestamp of the latest git commit.
///
/// Example: `0.1.0-abcd012-2038-01-19T03:14:08Z`.
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! version {
() => {
concat!(
env!("VERGEN_GIT_DESCRIBE"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
)
};
}
/// A string uniquely identifying the application build.
///
/// Consists of a combination of:
/// - Version defined in the crate file
/// - Timestamp of commit
/// - Hash of the commit
/// - Version of rust compiler
/// - Target triple
///
/// Example: `0.1.0-f5f383e-2022-09-04T11:39:37Z-1.63.0-x86_64-unknown-linux-gnu`
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! build {
() => {
concat!(
env!("CARGO_PKG_VERSION"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
"-",
env!("VERGEN_RUSTC_SEMVER"),
"-",
$crate::profile!(),
"-",
env!("VERGEN_CARGO_TARGET_TRIPLE"),
)
};
}
/// Short hash of the current commit.
///
/// Example: `f5f383e`.
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! commit {
() => {
env!("VERGEN_GIT_SHA")
};
}
// /// Information about the platform on which service was built, including:
// /// - Information about OS
// /// - Information about CPU
// ///
// /// Example: ``.
// #[macro_export]
// macro_rules! platform {
// (
// ) => {
// concat!(
// env!("VERGEN_SYSINFO_OS_VERSION"),
// " - ",
// env!("VERGEN_SYSINFO_CPU_BRAND"),
// )
// };
// }
/// Service name deduced from name of the binary.
/// This macro must be called within binaries only.
///
/// Example: `router`.
#[macro_export]
macro_rules! service_name {
() => {
env!("CARGO_BIN_NAME")
};
}
/// Build profile, either debug or release.
///
/// Example: `release`.
#[macro_export]
macro_rules! profile {
() => {
env!("CARGO_PROFILE")
};
}
/// The latest git tag. If tags are not present in the repository, the short commit hash is used
/// instead. Refer to the [`git describe`](https://git-scm.com/docs/git-describe) documentation for
/// more details.
#[macro_export]
macro_rules! git_tag {
() => {
env!("VERGEN_GIT_DESCRIBE")
};
}
| 1,186 | 1,066 |
hyperswitch | crates/router_env/src/logger.rs | .rs | //! Logger of the system.
pub use tracing::{debug, error, event as log, info, warn};
pub use tracing_attributes::instrument;
pub mod config;
mod defaults;
pub use crate::config::Config;
// mod macros;
pub mod types;
pub use types::{Category, Flow, Level, Tag};
mod setup;
pub use setup::{setup, TelemetryGuard};
pub mod formatter;
pub use formatter::FormattingLayer;
pub mod storage;
pub use storage::{Storage, StorageSubscription};
| 101 | 1,067 |
hyperswitch | crates/router_env/src/lib.rs | .rs | #![warn(missing_debug_implementations)]
//! Environment of payment router: logger, basic config, its environment awareness.
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
/// Utilities to identify members of the current cargo workspace.
pub mod cargo_workspace;
pub mod env;
pub mod logger;
pub mod metrics;
/// `cargo` build instructions generation for obtaining information about the application
/// environment.
#[cfg(feature = "vergen")]
pub mod vergen;
// pub use literally;
#[doc(inline)]
pub use logger::*;
pub use once_cell;
pub use opentelemetry;
pub use tracing;
#[cfg(feature = "actix_web")]
pub use tracing_actix_web;
pub use tracing_appender;
#[doc(inline)]
pub use self::env::*;
| 168 | 1,068 |
hyperswitch | crates/router_env/src/logger/setup.rs | .rs | //! Setup logging subsystem.
use std::time::Duration;
use ::config::ConfigError;
use serde_json::ser::{CompactFormatter, PrettyFormatter};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer};
use crate::{config, FormattingLayer, StorageSubscription};
/// Contains guards necessary for logging and metrics collection.
#[derive(Debug)]
pub struct TelemetryGuard {
_log_guards: Vec<WorkerGuard>,
}
/// Setup logging sub-system specifying the logging configuration, service (binary) name, and a
/// list of external crates for which a more verbose logging must be enabled. All crates within the
/// current cargo workspace are automatically considered for verbose logging.
#[allow(clippy::print_stdout)] // The logger hasn't been initialized yet
pub fn setup(
config: &config::Log,
service_name: &str,
crates_to_filter: impl AsRef<[&'static str]>,
) -> error_stack::Result<TelemetryGuard, ConfigError> {
let mut guards = Vec::new();
// Setup OpenTelemetry traces and metrics
let traces_layer = if config.telemetry.traces_enabled {
setup_tracing_pipeline(&config.telemetry, service_name)
} else {
None
};
if config.telemetry.metrics_enabled {
setup_metrics_pipeline(&config.telemetry)
};
// Setup file logging
let file_writer = if config.file.enabled {
let mut path = crate::env::workspace_path();
// Using an absolute path for file log path would replace workspace path with absolute path,
// which is the intended behavior for us.
path.push(&config.file.path);
let file_appender = tracing_appender::rolling::hourly(&path, &config.file.file_name);
let (file_writer, guard) = tracing_appender::non_blocking(file_appender);
guards.push(guard);
let file_filter = get_envfilter(
config.file.filtering_directive.as_ref(),
config::Level(tracing::Level::WARN),
config.file.level,
&crates_to_filter,
);
println!("Using file logging filter: {file_filter}");
let layer = FormattingLayer::new(service_name, file_writer, CompactFormatter)?
.with_filter(file_filter);
Some(layer)
} else {
None
};
let subscriber = tracing_subscriber::registry()
.with(traces_layer)
.with(StorageSubscription)
.with(file_writer);
// Setup console logging
if config.console.enabled {
let (console_writer, guard) = tracing_appender::non_blocking(std::io::stdout());
guards.push(guard);
let console_filter = get_envfilter(
config.console.filtering_directive.as_ref(),
config::Level(tracing::Level::WARN),
config.console.level,
&crates_to_filter,
);
println!("Using console logging filter: {console_filter}");
match config.console.log_format {
config::LogFormat::Default => {
let logging_layer = fmt::layer()
.with_timer(fmt::time::time())
.pretty()
.with_writer(console_writer)
.with_filter(console_filter);
subscriber.with(logging_layer).init();
}
config::LogFormat::Json => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
subscriber
.with(
FormattingLayer::new(service_name, console_writer, CompactFormatter)?
.with_filter(console_filter),
)
.init();
}
config::LogFormat::PrettyJson => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
subscriber
.with(
FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())?
.with_filter(console_filter),
)
.init();
}
}
} else {
subscriber.init();
};
// Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is
// dropped
Ok(TelemetryGuard {
_log_guards: guards,
})
}
fn get_opentelemetry_exporter_config(
config: &config::LogTelemetry,
) -> opentelemetry_otlp::ExportConfig {
let mut exporter_config = opentelemetry_otlp::ExportConfig {
protocol: opentelemetry_otlp::Protocol::Grpc,
endpoint: config.otel_exporter_otlp_endpoint.clone(),
..Default::default()
};
if let Some(timeout) = config.otel_exporter_otlp_timeout {
exporter_config.timeout = Duration::from_millis(timeout);
}
exporter_config
}
#[derive(Debug, Clone)]
enum TraceUrlAssert {
Match(String),
EndsWith(String),
}
impl TraceUrlAssert {
fn compare_url(&self, url: &str) -> bool {
match self {
Self::Match(value) => url == value,
Self::EndsWith(end) => url.ends_with(end),
}
}
}
impl From<String> for TraceUrlAssert {
fn from(value: String) -> Self {
match value {
url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()),
url => Self::Match(url),
}
}
}
#[derive(Debug, Clone)]
struct TraceAssertion {
clauses: Option<Vec<TraceUrlAssert>>,
/// default behaviour for tracing if no condition is provided
default: bool,
}
impl TraceAssertion {
/// Should the provided url be traced
fn should_trace_url(&self, url: &str) -> bool {
match &self.clauses {
Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)),
None => self.default,
}
}
}
/// Conditional Sampler for providing control on url based tracing
#[derive(Clone, Debug)]
struct ConditionalSampler<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>(
TraceAssertion,
T,
);
impl<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>
opentelemetry_sdk::trace::ShouldSample for ConditionalSampler<T>
{
fn should_sample(
&self,
parent_context: Option<&opentelemetry::Context>,
trace_id: opentelemetry::trace::TraceId,
name: &str,
span_kind: &opentelemetry::trace::SpanKind,
attributes: &[opentelemetry::KeyValue],
links: &[opentelemetry::trace::Link],
) -> opentelemetry::trace::SamplingResult {
use opentelemetry::trace::TraceContextExt;
match attributes
.iter()
.find(|&kv| kv.key == opentelemetry::Key::new("http.route"))
.map_or(self.0.default, |inner| {
self.0.should_trace_url(&inner.value.as_str())
}) {
true => {
self.1
.should_sample(parent_context, trace_id, name, span_kind, attributes, links)
}
false => opentelemetry::trace::SamplingResult {
decision: opentelemetry::trace::SamplingDecision::Drop,
attributes: Vec::new(),
trace_state: match parent_context {
Some(ctx) => ctx.span().span_context().trace_state().clone(),
None => opentelemetry::trace::TraceState::default(),
},
},
}
}
}
fn setup_tracing_pipeline(
config: &config::LogTelemetry,
service_name: &str,
) -> Option<
tracing_opentelemetry::OpenTelemetryLayer<
tracing_subscriber::Registry,
opentelemetry_sdk::trace::Tracer,
>,
> {
use opentelemetry::trace::TracerProvider;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::trace;
opentelemetry::global::set_text_map_propagator(
opentelemetry_sdk::propagation::TraceContextPropagator::new(),
);
// Set the export interval to 1 second
let batch_config = trace::BatchConfigBuilder::default()
.with_scheduled_delay(Duration::from_millis(1000))
.build();
let exporter_result = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_export_config(get_opentelemetry_exporter_config(config))
.build();
let exporter = if config.ignore_errors {
#[allow(clippy::print_stderr)] // The logger hasn't been initialized yet
exporter_result
.inspect_err(|error| eprintln!("Failed to build traces exporter: {error:?}"))
.ok()?
} else {
// Safety: This is conditional, there is an option to avoid this behavior at runtime.
#[allow(clippy::expect_used)]
exporter_result.expect("Failed to build traces exporter")
};
let mut provider_builder = trace::TracerProvider::builder()
.with_span_processor(
trace::BatchSpanProcessor::builder(
exporter,
// The runtime would have to be updated if a different web framework is used
opentelemetry_sdk::runtime::TokioCurrentThread,
)
.with_batch_config(batch_config)
.build(),
)
.with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler(
TraceAssertion {
clauses: config
.route_to_trace
.clone()
.map(|inner| inner.into_iter().map(TraceUrlAssert::from).collect()),
default: false,
},
trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)),
))))
.with_resource(opentelemetry_sdk::Resource::new(vec![
opentelemetry::KeyValue::new("service.name", service_name.to_owned()),
]));
if config.use_xray_generator {
provider_builder = provider_builder
.with_id_generator(opentelemetry_aws::trace::XrayIdGenerator::default());
}
Some(
tracing_opentelemetry::layer()
.with_tracer(provider_builder.build().tracer(service_name.to_owned())),
)
}
fn setup_metrics_pipeline(config: &config::LogTelemetry) {
use opentelemetry_otlp::WithExportConfig;
let exporter_result = opentelemetry_otlp::MetricExporter::builder()
.with_tonic()
.with_temporality(opentelemetry_sdk::metrics::Temporality::Cumulative)
.with_export_config(get_opentelemetry_exporter_config(config))
.build();
let exporter = if config.ignore_errors {
#[allow(clippy::print_stderr)] // The logger hasn't been initialized yet
exporter_result
.inspect_err(|error| eprintln!("Failed to build metrics exporter: {error:?}"))
.ok();
return;
} else {
// Safety: This is conditional, there is an option to avoid this behavior at runtime.
#[allow(clippy::expect_used)]
exporter_result.expect("Failed to build metrics exporter")
};
let reader = opentelemetry_sdk::metrics::PeriodicReader::builder(
exporter,
// The runtime would have to be updated if a different web framework is used
opentelemetry_sdk::runtime::TokioCurrentThread,
)
.with_interval(Duration::from_secs(3))
.with_timeout(Duration::from_secs(10))
.build();
let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
.with_reader(reader)
.with_resource(opentelemetry_sdk::Resource::new([
opentelemetry::KeyValue::new(
"pod",
std::env::var("POD_NAME").unwrap_or(String::from("hyperswitch-server-default")),
),
]))
.build();
opentelemetry::global::set_meter_provider(provider);
}
fn get_envfilter(
filtering_directive: Option<&String>,
default_log_level: config::Level,
filter_log_level: config::Level,
crates_to_filter: impl AsRef<[&'static str]>,
) -> EnvFilter {
filtering_directive
.map(|filter| {
// Try to create target filter from specified filtering directive, if set
// Safety: If user is overriding the default filtering directive, then we need to panic
// for invalid directives.
#[allow(clippy::expect_used)]
EnvFilter::builder()
.with_default_directive(default_log_level.into_level().into())
.parse(filter)
.expect("Invalid EnvFilter filtering directive")
})
.unwrap_or_else(|| {
// Construct a default target filter otherwise
let mut workspace_members = crate::cargo_workspace_members!();
workspace_members.extend(crates_to_filter.as_ref());
workspace_members
.drain()
.zip(std::iter::repeat(filter_log_level.into_level()))
.fold(
EnvFilter::default().add_directive(default_log_level.into_level().into()),
|env_filter, (target, level)| {
// Safety: This is a hardcoded basic filtering directive. If even the basic
// filter is wrong, it's better to panic.
#[allow(clippy::expect_used)]
env_filter.add_directive(
format!("{target}={level}")
.parse()
.expect("Invalid EnvFilter directive format"),
)
},
)
})
}
| 2,837 | 1,069 |
hyperswitch | crates/router_env/src/logger/formatter.rs | .rs | //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
use std::{
collections::{HashMap, HashSet},
fmt,
io::Write,
};
use config::ConfigError;
use once_cell::sync::Lazy;
use serde::ser::{SerializeMap, Serializer};
use serde_json::{ser::Formatter, Value};
// use time::format_description::well_known::Rfc3339;
use time::format_description::well_known::Iso8601;
use tracing::{Event, Metadata, Subscriber};
use tracing_subscriber::{
fmt::MakeWriter,
layer::Context,
registry::{LookupSpan, SpanRef},
Layer,
};
use crate::Storage;
// TODO: Documentation coverage for this crate
// Implicit keys
const MESSAGE: &str = "message";
const HOSTNAME: &str = "hostname";
const PID: &str = "pid";
const ENV: &str = "env";
const VERSION: &str = "version";
const BUILD: &str = "build";
const LEVEL: &str = "level";
const TARGET: &str = "target";
const SERVICE: &str = "service";
const LINE: &str = "line";
const FILE: &str = "file";
const FN: &str = "fn";
const FULL_NAME: &str = "full_name";
const TIME: &str = "time";
// Extra implicit keys. Keys that are provided during runtime but should be treated as
// implicit in the logs
const FLOW: &str = "flow";
const MERCHANT_AUTH: &str = "merchant_authentication";
const MERCHANT_ID: &str = "merchant_id";
const REQUEST_METHOD: &str = "request_method";
const REQUEST_URL_PATH: &str = "request_url_path";
const REQUEST_ID: &str = "request_id";
const WORKFLOW_ID: &str = "workflow_id";
const GLOBAL_ID: &str = "global_id";
const SESSION_ID: &str = "session_id";
/// Set of predefined implicit keys.
pub static IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(HOSTNAME);
set.insert(PID);
set.insert(ENV);
set.insert(VERSION);
set.insert(BUILD);
set.insert(LEVEL);
set.insert(TARGET);
set.insert(SERVICE);
set.insert(LINE);
set.insert(FILE);
set.insert(FN);
set.insert(FULL_NAME);
set.insert(TIME);
set
});
/// Extra implicit keys. Keys that are not purely implicit but need to be logged alongside
/// other implicit keys in the log json.
pub static EXTRA_IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(MESSAGE);
set.insert(FLOW);
set.insert(MERCHANT_AUTH);
set.insert(MERCHANT_ID);
set.insert(REQUEST_METHOD);
set.insert(REQUEST_URL_PATH);
set.insert(REQUEST_ID);
set.insert(GLOBAL_ID);
set.insert(SESSION_ID);
set.insert(WORKFLOW_ID);
set
});
/// Describe type of record: entering a span, exiting a span, an event.
#[derive(Clone, Debug)]
pub enum RecordType {
/// Entering a span.
EnterSpan,
/// Exiting a span.
ExitSpan,
/// Event.
Event,
}
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
Self::EnterSpan => "START",
Self::ExitSpan => "END",
Self::Event => "EVENT",
};
write!(f, "{repr}")
}
}
/// Format log records.
/// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries.
#[derive(Debug)]
pub struct FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone,
{
dst_writer: W,
pid: u32,
hostname: String,
env: String,
service: String,
#[cfg(feature = "vergen")]
version: String,
#[cfg(feature = "vergen")]
build: String,
default_fields: HashMap<String, Value>,
formatter: F,
}
impl<W, F> FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone,
{
/// Constructor of `FormattingLayer`.
///
/// A `name` will be attached to all records during formatting.
/// A `dst_writer` to forward all records.
///
/// ## Example
/// ```rust
/// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter);
/// ```
pub fn new(
service: &str,
dst_writer: W,
formatter: F,
) -> error_stack::Result<Self, ConfigError> {
Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter)
}
/// Construct of `FormattingLayer with implicit default entries.
pub fn new_with_implicit_entries(
service: &str,
dst_writer: W,
default_fields: HashMap<String, Value>,
formatter: F,
) -> error_stack::Result<Self, ConfigError> {
let pid = std::process::id();
let hostname = gethostname::gethostname().to_string_lossy().into_owned();
let service = service.to_string();
#[cfg(feature = "vergen")]
let version = crate::version!().to_string();
#[cfg(feature = "vergen")]
let build = crate::build!().to_string();
let env = crate::env::which().to_string();
for key in default_fields.keys() {
if IMPLICIT_KEYS.contains(key.as_str()) {
return Err(ConfigError::Message(format!(
"A reserved key `{key}` was included in `default_fields` in the log formatting layer"
))
.into());
}
}
Ok(Self {
dst_writer,
pid,
hostname,
env,
service,
#[cfg(feature = "vergen")]
version,
#[cfg(feature = "vergen")]
build,
default_fields,
formatter,
})
}
/// Serialize common for both span and event entries.
fn common_serialize<S>(
&self,
map_serializer: &mut impl SerializeMap<Error = serde_json::Error>,
metadata: &Metadata<'_>,
span: Option<&SpanRef<'_, S>>,
storage: &Storage<'_>,
name: &str,
) -> Result<(), std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s);
let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s);
map_serializer.serialize_entry(HOSTNAME, &self.hostname)?;
map_serializer.serialize_entry(PID, &self.pid)?;
map_serializer.serialize_entry(ENV, &self.env)?;
#[cfg(feature = "vergen")]
map_serializer.serialize_entry(VERSION, &self.version)?;
#[cfg(feature = "vergen")]
map_serializer.serialize_entry(BUILD, &self.build)?;
map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?;
map_serializer.serialize_entry(TARGET, metadata.target())?;
map_serializer.serialize_entry(SERVICE, &self.service)?;
map_serializer.serialize_entry(LINE, &metadata.line())?;
map_serializer.serialize_entry(FILE, &metadata.file())?;
map_serializer.serialize_entry(FN, name)?;
map_serializer
.serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?;
if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) {
map_serializer.serialize_entry(TIME, time)?;
}
// Write down implicit default entries.
for (key, value) in self.default_fields.iter() {
map_serializer.serialize_entry(key, value)?;
}
#[cfg(feature = "log_custom_entries_to_extra")]
let mut extra = serde_json::Map::default();
let mut explicit_entries_set: HashSet<&str> = HashSet::default();
// Write down explicit event's entries.
for (key, value) in storage.values.iter() {
if is_extra_implicit(key) {
#[cfg(feature = "log_extra_implicit_fields")]
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
} else if is_extra(key) {
#[cfg(feature = "log_custom_entries_to_extra")]
extra.insert(key.to_string(), value.clone());
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
} else {
tracing::warn!(
?key,
?value,
"Attempting to log a reserved entry. It won't be added to the logs"
);
}
}
// Write down entries from the span, if it exists.
if let Some(span) = &span {
let extensions = span.extensions();
if let Some(visitor) = extensions.get::<Storage<'_>>() {
for (key, value) in &visitor.values {
if is_extra_implicit(key) && !explicit_entries_set.contains(key) {
#[cfg(feature = "log_extra_implicit_fields")]
map_serializer.serialize_entry(key, value)?;
} else if is_extra(key) && !explicit_entries_set.contains(key) {
#[cfg(feature = "log_custom_entries_to_extra")]
extra.insert(key.to_string(), value.clone());
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
} else {
tracing::warn!(
?key,
?value,
"Attempting to log a reserved entry. It won't be added to the logs"
);
}
}
}
}
#[cfg(feature = "log_custom_entries_to_extra")]
map_serializer.serialize_entry("extra", &extra)?;
Ok(())
}
/// Flush memory buffer into an output stream trailing it with next line.
///
/// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading.
fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> {
buffer.write_all(b"\n")?;
self.dst_writer.make_writer().write_all(&buffer)
}
/// Serialize entries of span.
fn span_serialize<S>(
&self,
span: &SpanRef<'_, S>,
ty: RecordType,
) -> Result<Vec<u8>, std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let message = Self::span_message(span, ty);
let mut storage = Storage::default();
storage.record_value("message", message.into());
self.common_serialize(
&mut map_serializer,
span.metadata(),
Some(span),
&storage,
span.name(),
)?;
map_serializer.end()?;
Ok(buffer)
}
/// Serialize event into a buffer of bytes using parent span.
pub fn event_serialize<S>(
&self,
span: Option<&SpanRef<'_, S>>,
event: &Event<'_>,
) -> std::io::Result<Vec<u8>>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let mut storage = Storage::default();
event.record(&mut storage);
let name = span.map_or("?", SpanRef::name);
Self::event_message(span, event, &mut storage);
self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?;
map_serializer.end()?;
Ok(buffer)
}
/// Format message of a span.
///
/// Example: "[FN_WITHOUT_COLON - START]"
fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
format!("[{} - {}]", span.metadata().name().to_uppercase(), ty)
}
/// Format message of an event.
///
/// Examples: "[FN_WITHOUT_COLON - EVENT] Message"
fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>)
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
// Get value of kept "message" or "target" if does not exist.
let message = storage
.values
.entry("message")
.or_insert_with(|| event.metadata().target().into());
// Prepend the span name to the message if span exists.
if let (Some(span), Value::String(a)) = (span, message) {
*a = format!("{} {}", Self::span_message(span, RecordType::Event), a,);
}
}
}
#[allow(clippy::expect_used)]
impl<S, W, F> Layer<S> for FormattingLayer<W, F>
where
S: Subscriber + for<'a> LookupSpan<'a>,
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone + 'static,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
// Event could have no span.
let span = ctx.lookup_current();
let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event);
if let Ok(formatted) = result {
let _ = self.flush(formatted);
}
}
#[cfg(feature = "log_active_span_json")]
fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) {
let _ = self.flush(serialized);
}
}
#[cfg(not(feature = "log_active_span_json"))]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if span.parent().is_none() {
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
#[cfg(feature = "log_active_span_json")]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
| 3,367 | 1,070 |
hyperswitch | crates/router_env/src/logger/config.rs | .rs | //! Logger-specific config.
use std::path::PathBuf;
use serde::Deserialize;
/// Config settings.
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
/// Logging to a file.
pub log: Log,
}
/// Log config settings.
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Log {
/// Logging to a file.
pub file: LogFile,
/// Logging to a console.
pub console: LogConsole,
/// Telemetry / tracing.
pub telemetry: LogTelemetry,
}
/// Logging to a file.
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct LogFile {
/// Whether you want to store log in log files.
pub enabled: bool,
/// Where to store log files.
pub path: String,
/// Name of log file without suffix.
pub file_name: String,
/// What gets into log files.
pub level: Level,
/// Directive which sets the log level for one or more crates/modules.
pub filtering_directive: Option<String>,
// pub do_async: bool, // is not used
// pub rotation: u16,
}
/// Describes the level of verbosity of a span or event.
#[derive(Debug, Clone, Copy)]
pub struct Level(pub(super) tracing::Level);
impl Level {
/// Returns the most verbose [`tracing::Level`]
pub fn into_level(self) -> tracing::Level {
self.0
}
}
impl<'de> Deserialize<'de> for Level {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use std::str::FromStr as _;
let s = String::deserialize(deserializer)?;
tracing::Level::from_str(&s)
.map(Level)
.map_err(serde::de::Error::custom)
}
}
/// Logging to a console.
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct LogConsole {
/// Whether you want to see log in your terminal.
pub enabled: bool,
/// What you see in your terminal.
pub level: Level,
/// Log format
#[serde(default)]
pub log_format: LogFormat,
/// Directive which sets the log level for one or more crates/modules.
pub filtering_directive: Option<String>,
}
/// Telemetry / tracing.
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct LogTelemetry {
/// Whether the traces pipeline is enabled.
pub traces_enabled: bool,
/// Whether the metrics pipeline is enabled.
pub metrics_enabled: bool,
/// Whether errors in setting up traces or metrics pipelines must be ignored.
pub ignore_errors: bool,
/// Sampling rate for traces
pub sampling_rate: Option<f64>,
/// Base endpoint URL to send metrics and traces to. Can optionally include the port number.
pub otel_exporter_otlp_endpoint: Option<String>,
/// Timeout (in milliseconds) for sending metrics and traces.
pub otel_exporter_otlp_timeout: Option<u64>,
/// Whether to use xray ID generator, (enable this if you plan to use AWS-XRAY)
pub use_xray_generator: bool,
/// Route Based Tracing
pub route_to_trace: Option<Vec<String>>,
/// Interval for collecting the metrics (such as gauge) in background thread
pub bg_metrics_collection_interval_in_secs: Option<u16>,
}
/// Telemetry / tracing.
#[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LogFormat {
/// Default pretty log format
Default,
/// JSON based structured logging
#[default]
Json,
/// JSON based structured logging with pretty print
PrettyJson,
}
impl Config {
/// Default constructor.
pub fn new() -> Result<Self, config::ConfigError> {
Self::new_with_config_path(None)
}
/// Constructor expecting config path set explicitly.
pub fn new_with_config_path(
explicit_config_path: Option<PathBuf>,
) -> Result<Self, config::ConfigError> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `ROUTER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = crate::env::which();
let config_path = Self::config_path(&environment.to_string(), explicit_config_path);
let config = Self::builder(&environment.to_string())?
.add_source(config::File::from(config_path).required(false))
.add_source(config::Environment::with_prefix("ROUTER").separator("__"))
.build()?;
// The logger may not yet be initialized when constructing the application configuration
#[allow(clippy::print_stderr)]
serde_path_to_error::deserialize(config).map_err(|error| {
crate::error!(%error, "Unable to deserialize configuration");
eprintln!("Unable to deserialize application configuration: {error}");
error.into_inner()
})
}
/// Construct config builder extending it by fall-back defaults and setting config file to load.
pub fn builder(
environment: &str,
) -> Result<config::ConfigBuilder<config::builder::DefaultState>, config::ConfigError> {
config::Config::builder()
// Here, it should be `set_override()` not `set_default()`.
// "env" can't be altered by config field.
// Should be single source of truth.
.set_override("env", environment)
}
/// Config path.
pub fn config_path(environment: &str, explicit_config_path: Option<PathBuf>) -> PathBuf {
let mut config_path = PathBuf::new();
if let Some(explicit_config_path_val) = explicit_config_path {
config_path.push(explicit_config_path_val);
} else {
let config_file_name = match environment {
"production" => "production.toml",
"sandbox" => "sandbox.toml",
_ => "development.toml",
};
let config_directory = Self::get_config_directory();
config_path.push(config_directory);
config_path.push(config_file_name);
}
config_path
}
/// Get the Directory for the config file
/// Read the env variable `CONFIG_DIR` or fallback to `config`
pub fn get_config_directory() -> PathBuf {
let mut config_path = PathBuf::new();
let config_directory =
std::env::var(crate::env::vars::CONFIG_DIR).unwrap_or_else(|_| "config".into());
config_path.push(crate::env::workspace_path());
config_path.push(config_directory);
config_path
}
}
| 1,570 | 1,071 |
hyperswitch | crates/router_env/src/logger/defaults.rs | .rs | impl Default for super::config::LogFile {
fn default() -> Self {
Self {
enabled: true,
path: "logs".into(),
file_name: "debug.log".into(),
level: super::config::Level(tracing::Level::DEBUG),
filtering_directive: None,
}
}
}
impl Default for super::config::LogConsole {
fn default() -> Self {
Self {
enabled: false,
level: super::config::Level(tracing::Level::INFO),
log_format: super::config::LogFormat::Json,
filtering_directive: None,
}
}
}
| 134 | 1,072 |
hyperswitch | crates/router_env/src/logger/types.rs | .rs | //! Types.
use serde::Deserialize;
use strum::{Display, EnumString};
pub use tracing::{
field::{Field, Visit},
Level, Value,
};
/// Category and tag of log event.
///
/// Don't hesitate to add your variant if it is missing here.
#[derive(Debug, Default, Deserialize, Clone, Display, EnumString)]
pub enum Tag {
/// General.
#[default]
General,
/// Redis: get.
RedisGet,
/// Redis: set.
RedisSet,
/// API: incoming web request.
ApiIncomingRequest,
/// API: outgoing web request.
ApiOutgoingRequest,
/// Data base: create.
DbCreate,
/// Data base: read.
DbRead,
/// Data base: updare.
DbUpdate,
/// Data base: delete.
DbDelete,
/// Begin Request
BeginRequest,
/// End Request
EndRequest,
/// Call initiated to connector.
InitiatedToConnector,
/// Event: general.
Event,
/// Compatibility Layer Request
CompatibilityLayerRequest,
}
/// API Flow
#[derive(Debug, Display, Clone, PartialEq, Eq)]
pub enum Flow {
/// Health check
HealthCheck,
/// Deep health Check
DeepHealthCheck,
/// Organization create flow
OrganizationCreate,
/// Organization retrieve flow
OrganizationRetrieve,
/// Organization update flow
OrganizationUpdate,
/// Merchants account create flow.
MerchantsAccountCreate,
/// Merchants account retrieve flow.
MerchantsAccountRetrieve,
/// Merchants account update flow.
MerchantsAccountUpdate,
/// Merchants account delete flow.
MerchantsAccountDelete,
/// Merchant Connectors create flow.
MerchantConnectorsCreate,
/// Merchant Connectors retrieve flow.
MerchantConnectorsRetrieve,
/// Merchant account list
MerchantAccountList,
/// Merchant Connectors update flow.
MerchantConnectorsUpdate,
/// Merchant Connectors delete flow.
MerchantConnectorsDelete,
/// Merchant Connectors list flow.
MerchantConnectorsList,
/// Merchant Transfer Keys
MerchantTransferKey,
/// ConfigKey create flow.
ConfigKeyCreate,
/// ConfigKey fetch flow.
ConfigKeyFetch,
/// Enable platform account flow.
EnablePlatformAccount,
/// ConfigKey Update flow.
ConfigKeyUpdate,
/// ConfigKey Delete flow.
ConfigKeyDelete,
/// Customers create flow.
CustomersCreate,
/// Customers retrieve flow.
CustomersRetrieve,
/// Customers update flow.
CustomersUpdate,
/// Customers delete flow.
CustomersDelete,
/// Customers get mandates flow.
CustomersGetMandates,
/// Create an Ephemeral Key.
EphemeralKeyCreate,
/// Delete an Ephemeral Key.
EphemeralKeyDelete,
/// Mandates retrieve flow.
MandatesRetrieve,
/// Mandates revoke flow.
MandatesRevoke,
/// Mandates list flow.
MandatesList,
/// Payment methods create flow.
PaymentMethodsCreate,
/// Payment methods migrate flow.
PaymentMethodsMigrate,
/// Payment methods list flow.
PaymentMethodsList,
/// Payment method save flow
PaymentMethodSave,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// List Customers for a merchant
CustomersList,
/// Retrieve countries and currencies for connector and payment method
ListCountriesCurrencies,
/// Payment method create collect link flow.
PaymentMethodCollectLink,
/// Payment methods retrieve flow.
PaymentMethodsRetrieve,
/// Payment methods update flow.
PaymentMethodsUpdate,
/// Payment methods delete flow.
PaymentMethodsDelete,
/// Default Payment method flow.
DefaultPaymentMethodsSet,
/// Payments create flow.
PaymentsCreate,
/// Payments Retrieve flow.
PaymentsRetrieve,
/// Payments Retrieve force sync flow.
PaymentsRetrieveForceSync,
/// Payments Retrieve using merchant reference id
PaymentsRetrieveUsingMerchantReferenceId,
/// Payments update flow.
PaymentsUpdate,
/// Payments confirm flow.
PaymentsConfirm,
/// Payments capture flow.
PaymentsCapture,
/// Payments cancel flow.
PaymentsCancel,
/// Payments approve flow.
PaymentsApprove,
/// Payments reject flow.
PaymentsReject,
/// Payments Session Token flow
PaymentsSessionToken,
/// Payments start flow.
PaymentsStart,
/// Payments list flow.
PaymentsList,
/// Payments filters flow
PaymentsFilters,
/// Payments aggregates flow
PaymentsAggregate,
/// Payments Create Intent flow
PaymentsCreateIntent,
/// Payments Get Intent flow
PaymentsGetIntent,
/// Payments Update Intent flow
PaymentsUpdateIntent,
/// Payments confirm intent flow
PaymentsConfirmIntent,
/// Payments create and confirm intent flow
PaymentsCreateAndConfirmIntent,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
#[cfg(feature = "payouts")]
/// Payouts retrieve flow.
PayoutsRetrieve,
#[cfg(feature = "payouts")]
/// Payouts update flow.
PayoutsUpdate,
/// Payouts confirm flow.
PayoutsConfirm,
#[cfg(feature = "payouts")]
/// Payouts cancel flow.
PayoutsCancel,
#[cfg(feature = "payouts")]
/// Payouts fulfill flow.
PayoutsFulfill,
#[cfg(feature = "payouts")]
/// Payouts list flow.
PayoutsList,
#[cfg(feature = "payouts")]
/// Payouts filter flow.
PayoutsFilter,
/// Payouts accounts flow.
PayoutsAccounts,
/// Payout link initiate flow
PayoutLinkInitiate,
/// Payments Redirect flow
PaymentsRedirect,
/// Payemnts Complete Authorize Flow
PaymentsCompleteAuthorize,
/// Refunds create flow.
RefundsCreate,
/// Refunds retrieve flow.
RefundsRetrieve,
/// Refunds retrieve force sync flow.
RefundsRetrieveForceSync,
/// Refunds update flow.
RefundsUpdate,
/// Refunds list flow.
RefundsList,
/// Refunds filters flow
RefundsFilters,
/// Refunds aggregates flow
RefundsAggregate,
// Retrieve forex flow.
RetrieveForexFlow,
/// Toggles recon service for a merchant.
ReconMerchantUpdate,
/// Recon token request flow.
ReconTokenRequest,
/// Initial request for recon service.
ReconServiceRequest,
/// Recon token verification flow
ReconVerifyToken,
/// Routing create flow,
RoutingCreateConfig,
/// Routing link config
RoutingLinkConfig,
/// Routing link config
RoutingUnlinkConfig,
/// Routing retrieve config
RoutingRetrieveConfig,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
/// Routing retrieve default config
RoutingRetrieveDefaultConfig,
/// Routing retrieve dictionary
RoutingRetrieveDictionary,
/// Routing update config
RoutingUpdateConfig,
/// Routing update default config
RoutingUpdateDefaultConfig,
/// Routing delete config
RoutingDeleteConfig,
/// Toggle dynamic routing
ToggleDynamicRouting,
/// Update dynamic routing config
UpdateDynamicRoutingConfigs,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
DeleteFromBlocklist,
/// List entries from blocklist
ListBlocklist,
/// Toggle blocklist for merchant
ToggleBlocklistGuard,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive
RecoveryIncomingWebhookReceive,
/// Validate payment method flow
ValidatePaymentMethod,
/// API Key create flow
ApiKeyCreate,
/// API Key retrieve flow
ApiKeyRetrieve,
/// API Key update flow
ApiKeyUpdate,
/// API Key revoke flow
ApiKeyRevoke,
/// API Key list flow
ApiKeyList,
/// Dispute Retrieve flow
DisputesRetrieve,
/// Dispute List flow
DisputesList,
/// Dispute Filters flow
DisputesFilters,
/// Cards Info flow
CardsInfo,
/// Create File flow
CreateFile,
/// Delete File flow
DeleteFile,
/// Retrieve File flow
RetrieveFile,
/// Dispute Evidence submission flow
DisputesEvidenceSubmit,
/// Create Config Key flow
CreateConfigKey,
/// Attach Dispute Evidence flow
AttachDisputeEvidence,
/// Delete Dispute Evidence flow
DeleteDisputeEvidence,
/// Disputes aggregate flow
DisputesAggregate,
/// Retrieve Dispute Evidence flow
RetrieveDisputeEvidence,
/// Invalidate cache flow
CacheInvalidate,
/// Payment Link Retrieve flow
PaymentLinkRetrieve,
/// payment Link Initiate flow
PaymentLinkInitiate,
/// payment Link Initiate flow
PaymentSecureLinkInitiate,
/// Payment Link List flow
PaymentLinkList,
/// Payment Link Status
PaymentLinkStatus,
/// Create a profile
ProfileCreate,
/// Update a profile
ProfileUpdate,
/// Retrieve a profile
ProfileRetrieve,
/// Delete a profile
ProfileDelete,
/// List all the profiles for a merchant
ProfileList,
/// Different verification flows
Verification,
/// Rust locker migration
RustLockerMigration,
/// Gsm Rule Creation flow
GsmRuleCreate,
/// Gsm Rule Retrieve flow
GsmRuleRetrieve,
/// Gsm Rule Update flow
GsmRuleUpdate,
/// Apple pay certificates migration
ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// User Sign Up
UserSignUp,
/// User Sign Up
UserSignUpWithMerchantId,
/// User Sign In
UserSignIn,
/// User transfer key
UserTransferKey,
/// User connect account
UserConnectAccount,
/// Upsert Decision Manager Config
DecisionManagerUpsertConfig,
/// Delete Decision Manager Config
DecisionManagerDeleteConfig,
/// Retrieve Decision Manager Config
DecisionManagerRetrieveConfig,
/// Manual payment fulfillment acknowledgement
FrmFulfillment,
/// Get connectors feature matrix
FeatureMatrix,
/// Change password flow
ChangePassword,
/// Signout flow
Signout,
/// Set Dashboard Metadata flow
SetDashboardMetadata,
/// Get Multiple Dashboard Metadata flow
GetMultipleDashboardMetadata,
/// Payment Connector Verify
VerifyPaymentConnector,
/// Internal user signup
InternalUserSignup,
/// Create tenant level user
TenantUserCreate,
/// Switch org
SwitchOrg,
/// Switch merchant v2
SwitchMerchantV2,
/// Switch profile
SwitchProfile,
/// Get permission info
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
/// Get Parent Group Info
GetParentGroupInfo,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
ListInvitableRolesAtEntityLevel,
/// List updatable roles at entity level
ListUpdatableRolesAtEntityLevel,
/// Get role
GetRole,
/// Get parent info for role
GetRoleV2,
/// Get role from token
GetRoleFromToken,
/// Get resources and groups for role from token
GetRoleFromTokenV2,
/// Update user role
UpdateUserRole,
/// Create merchant account for user in a org
UserMerchantAccountCreate,
/// Create Org in a given tenancy
UserOrgMerchantCreate,
/// Generate Sample Data
GenerateSampleData,
/// Delete Sample Data
DeleteSampleData,
/// Get details of a user
GetUserDetails,
/// Get details of a user role in a merchant account
GetUserRoleDetails,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
PmAuthExchangeToken,
/// Get reset password link
ForgotPassword,
/// Reset password using link
ResetPassword,
/// Force set or force change password
RotatePassword,
/// Invite multiple users
InviteMultipleUser,
/// Reinvite user
ReInviteUser,
/// Accept invite from email
AcceptInviteFromEmail,
/// Delete user role
DeleteUserRole,
/// Incremental Authorization flow
PaymentsIncrementalAuthorization,
/// Get action URL for connector onboarding
GetActionUrl,
/// Sync connector onboarding status
SyncOnboardingStatus,
/// Reset tracking id
ResetTrackingId,
/// Verify email Token
VerifyEmail,
/// Send verify email
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
/// Accept user invitation using entities
AcceptInvitationsV2,
/// Accept user invitation using entities before user login
AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
PaymentsExternalAuthentication,
/// Authorize the payment after external 3ds authentication
PaymentsAuthorize,
/// Create Role
CreateRole,
/// Update Role
UpdateRole,
/// User email flow start
UserFromEmail,
/// Begin TOTP
TotpBegin,
/// Reset TOTP
TotpReset,
/// Verify TOTP
TotpVerify,
/// Update TOTP secret
TotpUpdate,
/// Verify Access Code
RecoveryCodeVerify,
/// Generate or Regenerate recovery codes
RecoveryCodesGenerate,
/// Terminate two factor authentication
TerminateTwoFactorAuth,
/// Check 2FA status
TwoFactorAuthStatus,
/// Create user authentication method
CreateUserAuthenticationMethod,
/// Update user authentication method
UpdateUserAuthenticationMethod,
/// List user authentication methods
ListUserAuthenticationMethods,
/// Get sso auth url
GetSsoAuthUrl,
/// Signin with SSO
SignInWithSso,
/// Auth Select
AuthSelect,
/// List Orgs for user
ListOrgForUser,
/// List Merchants for user in org
ListMerchantsForUserInOrg,
/// List Profile for user in org and merchant
ListProfileForUserInOrgAndMerchant,
/// List Users in Org
ListUsersInLineage,
/// List invitations for user
ListInvitationsForUser,
/// Get theme using lineage
GetThemeUsingLineage,
/// Get theme using theme id
GetThemeUsingThemeId,
/// Upload file to theme storage
UploadFileToThemeStorage,
/// Create theme
CreateTheme,
/// Update theme
UpdateTheme,
/// Delete theme
DeleteTheme,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
WebhookEventDeliveryAttemptList,
/// Manually retry the delivery for a webhook event
WebhookEventDeliveryRetry,
/// Retrieve status of the Poll
RetrievePollStatus,
/// Toggles the extended card info feature in profile level
ToggleExtendedCardInfo,
/// Toggles the extended card info feature in profile level
ToggleConnectorAgnosticMit,
/// Get the extended card info associated to a payment_id
GetExtendedCardInfo,
/// Manually update the refund details like status, error code, error message etc.
RefundsManualUpdate,
/// Manually update the payment details like status, error code, error message etc.
PaymentsManualUpdate,
/// Dynamic Tax Calcultion
SessionUpdateTaxCalculation,
ProxyConfirmIntent,
/// Payments post session tokens flow
PaymentsPostSessionTokens,
/// Payments start redirection flow
PaymentStartRedirection,
/// Volume split on the routing type
VolumeSplitOnRoutingType,
/// Relay flow
Relay,
/// Relay retrieve flow
RelayRetrieve,
/// Card tokenization flow
TokenizeCard,
/// Card tokenization using payment method flow
TokenizeCardUsingPaymentMethodId,
/// Cards batch tokenization flow
TokenizeCardBatch,
/// Incoming Relay Webhook Receive
IncomingRelayWebhookReceive,
/// Generate Hypersense Token
HypersenseTokenRequest,
/// Verify Hypersense Token
HypersenseVerifyToken,
/// Signout Hypersense Token
HypersenseSignoutToken,
/// Payment Method Session Create
PaymentMethodSessionCreate,
/// Payment Method Session Retrieve
PaymentMethodSessionRetrieve,
// Payment Method Session Update
PaymentMethodSessionUpdate,
/// Update a saved payment method using the payment methods session
PaymentMethodSessionUpdateSavedPaymentMethod,
/// Delete a saved payment method using the payment methods session
PaymentMethodSessionDeleteSavedPaymentMethod,
/// Confirm a payment method session with payment method data
PaymentMethodSessionConfirm,
/// Create Cards Info flow
CardsInfoCreate,
/// Update Cards Info flow
CardsInfoUpdate,
/// Cards Info migrate flow
CardsInfoMigrate,
///Total payment method count for merchant
TotalPaymentMethodCount,
/// Process Tracker Revenue Recovery Workflow Retrieve
RevenueRecoveryRetrieve,
}
/// Trait for providing generic behaviour to flow metric
pub trait FlowMetric: ToString + std::fmt::Debug + Clone {}
impl FlowMetric for Flow {}
/// Category of log event.
#[derive(Debug)]
pub enum Category {
/// Redis: general.
Redis,
/// API: general.
Api,
/// Database: general.
Store,
/// Event: general.
Event,
/// General: general.
General,
}
| 3,795 | 1,073 |
hyperswitch | crates/router_env/src/logger/storage.rs | .rs | //! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
use std::{collections::HashMap, fmt, time::Instant};
use tracing::{
field::{Field, Visit},
span::{Attributes, Record},
Id, Subscriber,
};
use tracing_subscriber::{layer::Context, Layer};
/// Storage to store key value pairs of spans.
#[derive(Clone, Debug)]
pub struct StorageSubscription;
/// Storage to store key value pairs of spans.
/// When new entry is crated it stores it in [HashMap] which is owned by `extensions`.
#[derive(Clone, Debug)]
pub struct Storage<'a> {
/// Hash map to store values.
pub values: HashMap<&'a str, serde_json::Value>,
}
impl<'a> Storage<'a> {
/// Default constructor.
pub fn new() -> Self {
Self::default()
}
pub fn record_value(&mut self, key: &'a str, value: serde_json::Value) {
if super::formatter::IMPLICIT_KEYS.contains(key) {
tracing::warn!(value =? value, "{} is a reserved entry. Skipping it.", key);
} else {
self.values.insert(key, value);
}
}
}
/// Default constructor.
impl Default for Storage<'_> {
fn default() -> Self {
Self {
values: HashMap::new(),
}
}
}
/// Visitor to store entry.
impl Visit for Storage<'_> {
/// A i64.
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A u64.
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A 64-bit floating point.
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A boolean.
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A string.
fn record_str(&mut self, field: &Field, value: &str) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// Otherwise.
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
match field.name() {
// Skip fields which are already handled
name if name.starts_with("log.") => (),
name if name.starts_with("r#") => {
self.record_value(
#[allow(clippy::expect_used)]
name.get(2..)
.expect("field name must have a minimum of two characters"),
serde_json::Value::from(format!("{value:?}")),
);
}
name => {
self.record_value(name, serde_json::Value::from(format!("{value:?}")));
}
};
}
}
const PERSISTENT_KEYS: [&str; 6] = [
"payment_id",
"connector_name",
"merchant_id",
"flow",
"payment_method",
"status_code",
];
impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S>
for StorageSubscription
{
/// On new span.
fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(id).expect("No span");
let mut extensions = span.extensions_mut();
let mut visitor = if let Some(parent_span) = span.parent() {
let mut extensions = parent_span.extensions_mut();
extensions
.get_mut::<Storage<'_>>()
.map(|v| v.to_owned())
.unwrap_or_default()
} else {
Storage::default()
};
attrs.record(&mut visitor);
extensions.insert(visitor);
}
/// On additional key value pairs store it.
fn on_record(&self, span: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(span).expect("No span");
let mut extensions = span.extensions_mut();
#[allow(clippy::expect_used)]
let visitor = extensions
.get_mut::<Storage<'_>>()
.expect("The span does not have storage");
values.record(visitor);
}
/// On enter store time.
fn on_enter(&self, span: &Id, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(span).expect("No span");
let mut extensions = span.extensions_mut();
if extensions.get_mut::<Instant>().is_none() {
extensions.insert(Instant::now());
}
}
/// On close create an entry about how long did it take.
fn on_close(&self, span: Id, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(&span).expect("No span");
let elapsed_milliseconds = {
let extensions = span.extensions();
extensions
.get::<Instant>()
.map(|i| i.elapsed().as_millis())
.unwrap_or(0)
};
if let Some(s) = span.extensions().get::<Storage<'_>>() {
s.values.iter().for_each(|(k, v)| {
if PERSISTENT_KEYS.contains(k) {
span.parent().and_then(|p| {
p.extensions_mut()
.get_mut::<Storage<'_>>()
.map(|s| s.record_value(k, v.to_owned()))
});
}
})
};
let mut extensions_mut = span.extensions_mut();
#[allow(clippy::expect_used)]
let visitor = extensions_mut
.get_mut::<Storage<'_>>()
.expect("No visitor in extensions");
if let Ok(elapsed) = serde_json::to_value(elapsed_milliseconds) {
visitor.record_value("elapsed_milliseconds", elapsed);
}
}
}
| 1,370 | 1,074 |
hyperswitch | crates/router/Cargo.toml | .toml | [package]
name = "router"
description = "Modern, fast and open payment router"
version = "0.2.0"
edition.workspace = true
default-run = "router"
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
default = ["common_default", "v1"]
common_default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "partial-auth", "km_forward_x_request_id"]
olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
tls = ["actix-web/rustls-0_22"]
email = ["external_services/email", "scheduler/email", "olap"]
# keymanager_create, keymanager_mtls, encryption_service should not be removed or added to default feature. Once this features were enabled it can't be disabled as these are breaking changes.
keymanager_create = []
keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"]
encryption_service = ["keymanager_create", "hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"]
km_forward_x_request_id = ["common_utils/km_forward_x_request_id"]
frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"]
stripe = []
release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing"]
oltp = ["storage_impl/oltp"]
kv_store = ["scheduler/kv_store"]
accounts_cache = []
vergen = ["router_env/vergen"]
dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "hyperswitch_interfaces/dummy_connector", "kgraph_utils/dummy_connector", "hyperswitch_domain_models/dummy_connector"]
external_access_dc = ["dummy_connector"]
detailed_errors = ["api_models/detailed_errors", "error-stack/serde"]
payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts"]
payout_retry = ["payouts"]
recon = ["email", "api_models/recon"]
retry = []
v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2","euclid/v2"]
v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"]
revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"]
refunds_v2 = ["diesel_models/refunds_v2", "storage_impl/refunds_v2"]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
# This is named as partial-auth because the router will still try to authenticate if the `x-merchant-id` header is not present.
partial-auth = []
[dependencies]
actix-cors = "0.6.5"
actix-http = "3.6.0"
actix-multipart = "0.6.1"
actix-rt = "2.9.0"
actix-web = "4.5.1"
argon2 = { version = "0.5.3", features = ["std"] }
async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" }
async-trait = "0.1.79"
base64 = "0.22.0"
bb8 = "0.8"
blake3 = "1.5.1"
bytes = "1.6.0"
clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] }
config = { version = "0.14.0", features = ["toml"] }
cookie = "0.18.1"
csv = "1.3.0"
diesel = { version = "2.2.3", features = ["postgres"] }
digest = "0.10.7"
dyn-clone = "1.0.17"
encoding_rs = "0.8.33"
error-stack = "0.4.1"
futures = "0.3.30"
hex = "0.4.3"
hkdf = "0.12.4"
http = "0.2.12"
hyper = "0.14.28"
infer = "0.15.0"
iso_currency = "0.4.4"
isocountry = "0.3.2"
josekit = "0.8.6"
jsonwebtoken = "9.2.0"
maud = { version = "0.26.0", features = ["actix-web"] }
mimalloc = { version = "0.1", optional = true }
mime = "0.3.17"
nanoid = "0.4.0"
num_cpus = "1.16.0"
num-traits = "0.2.19"
once_cell = "1.19.0"
openidconnect = "3.5.0" # TODO: remove reqwest
openssl = "0.10.70"
quick-xml = { version = "0.31.0", features = ["serialize"] }
rand = "0.8.5"
rand_chacha = "0.3.1"
rdkafka = "0.36.2"
regex = "1.10.4"
reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "multipart"] }
ring = "0.17.8"
rust_decimal = { version = "1.35.0", features = ["serde-with-float", "serde-with-str"] }
rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }
rustc-hash = "1.1.0"
rustls = "0.22"
rustls-pemfile = "2"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
serde_path_to_error = "0.1.16"
serde_qs = "0.12.0"
serde_repr = "0.1.19"
serde_urlencoded = "0.7.1"
serde_with = "3.7.0"
sha1 = { version = "0.10.6" }
sha2 = "0.10.8"
strum = { version = "0.26", features = ["derive"] }
tera = "1.19.1"
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std", "parsing", "serde-human-readable"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"] }
tracing-futures = { version = "0.2.5", features = ["tokio"] }
unicode-segmentation = "1.11.0"
unidecode = "0.3.0"
url = { version = "2.5.0", features = ["serde"] }
urlencoding = "2.1.3"
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] }
uuid = { version = "1.8.0", features = ["v4"] }
validator = "0.17.0"
x509-parser = "0.16.0"
# First party crates
analytics = { version = "0.1.0", path = "../analytics", optional = true, default-features = false }
api_models = { version = "0.1.0", path = "../api_models", features = ["errors", "control_center_theme"] }
cards = { version = "0.1.0", path = "../cards" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] }
common_types = { version = "0.1.0", path = "../common_types" }
currency_conversion = { version = "0.1.0", path = "../currency_conversion" }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }
euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] }
events = { version = "0.1.0", path = "../events" }
external_services = { version = "0.1.0", path = "../external_services" }
hyperswitch_connectors = { version = "0.1.0", path = "../hyperswitch_connectors", default-features = false }
hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" }
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" }
masking = { version = "0.1.0", path = "../masking" }
pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
router_derive = { version = "0.1.0", path = "../router_derive" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
scheduler = { version = "0.1.0", path = "../scheduler", default-features = false }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
payment_methods = { version = "0.1.0", path = "../payment_methods", default-features = false }
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
[dev-dependencies]
actix-http = "3.6.0"
awc = { version = "3.4.0", features = ["rustls"] }
derive_deref = "1.1.1"
rand = "0.8.5"
serial_test = "3.0.0"
time = { version = "0.3.35", features = ["macros"] }
tokio = "1.37.0"
wiremock = "0.6.0"
# First party dev-dependencies
test_utils = { version = "0.1.0", path = "../test_utils" }
[[bin]]
name = "router"
path = "src/bin/router.rs"
[[bin]]
name = "scheduler"
path = "src/bin/scheduler.rs"
[lints]
workspace = true
| 2,977 | 1,075 |
hyperswitch | crates/router/build.rs | .rs | fn main() {
// Set thread stack size to 10 MiB for debug builds
// Reference: https://doc.rust-lang.org/std/thread/#stack-size
#[cfg(debug_assertions)]
println!("cargo:rustc-env=RUST_MIN_STACK=10485760"); // 10 * 1024 * 1024 = 10 MiB
#[cfg(feature = "vergen")]
router_env::vergen::generate_cargo_instructions();
}
| 111 | 1,076 |
hyperswitch | crates/router/README.md | .md | # Router
Main crate of the project.
## Files Tree Layout
<!-- FIXME: this table should either be generated by a script or smoke test should be introduced checking it agrees with actual structure -->
<!-- FIXME: fill missing -->
```text
├── src : source code
│ ├── configs : config loading
│ ├── connector : various connector (gateway) specific transformations implementations.
│ │ ├── adyen : adyen connector
│ │ └── stripe : stripe connector
│ ├── core : the core router / orchestrator code. All common code/flow should exist here. only minimal code in connector implementations.
│ │ ├── customers : ?
│ │ ├── payment_methods : ?
│ │ ├── payments : ?
│ │ └── refunds : ?
│ ├── routes : the API endpoints exposed by router. currently uses actix_web.
│ ├── scheduler : ?
│ │ └── types : ?
│ ├── services : ?
│ │ └── redis : ?
│ ├── types : the objects/API type definitions
│ │ ├── api : the router API
│ │ └── storage : definitions for using DB/Storage. Currently uses Diesel.
│ └── utils : utilities
└── tests : unit and integration tests
```
<!--
command to generate the tree `tree -L 3 -d`
-->
| 313 | 1,077 |
hyperswitch | crates/router/locales/zh.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "您没有权限查看此内容"
title: "支付链接"
status:
title: "支付状态"
info:
ref_id: "参考ID"
error_code: "错误代码"
error_message: "错误信息"
message:
failed: "处理您的支付时失败。请与您的服务提供商确认更多详细信息。"
processing: "您的支付应在2-3个工作日内处理完毕。"
success: "您的支付已成功完成,使用了选定的支付方式。"
redirection_text:
redirecting: "正在重定向..."
redirecting_in: "重定向中"
seconds: "秒..."
text:
failed: "支付失败"
processing: "支付处理中"
success: "支付成功"
time:
am: "AM"
pm: "PM"
months:
january: "一月"
february: "二月"
march: "三月"
april: "四月"
may: "五月"
june: "六月"
july: "七月"
august: "八月"
september: "九月"
october: "十月"
november: "十一月"
december: "十二月"
| 282 | 1,078 |
hyperswitch | crates/router/locales/de.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Sie dürfen diesen Inhalt nicht anzeigen"
title: "Auszahlungslinks"
status:
title: "Auszahlungsstatus"
info:
ref_id: "Referenz-ID"
error_code: "Fehlercode"
error_message: "Fehlermeldung"
message:
failed: "Die Auszahlung konnte nicht verarbeitet werden. Bitte überprüfen Sie weitere Details bei Ihrem Anbieter."
processing: "Ihre Auszahlung sollte innerhalb von 2-3 Werktagen verarbeitet werden."
success: "Ihre Auszahlung wurde auf die ausgewählte Zahlungsmethode vorgenommen."
redirection_text:
redirecting: "Weiterleitung..."
redirecting_in: "Weiterleitung in"
seconds: "Sekunden..."
text:
failed: "Auszahlung fehlgeschlagen"
processing: "Auszahlung wird bearbeitet"
success: "Auszahlung erfolgreich"
time:
am: "AM"
pm: "PM"
months:
january: "Januar"
february: "Februar"
march: "März"
april: "April"
may: "Mai"
june: "Juni"
july: "Juli"
august: "August"
september: "September"
october: "Oktober"
november: "November"
december: "Dezember"
| 330 | 1,079 |
hyperswitch | crates/router/locales/es.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "No tienes permiso para ver este contenido"
title: "Enlaces de Pago"
status:
title: "Estado del Pago"
info:
ref_id: "ID de Referencia"
error_code: "Código de Error"
error_message: "Mensaje de Error"
message:
failed: "No se pudo procesar tu pago. Consulta con tu proveedor para más detalles."
processing: "Tu pago debería ser procesado en 2-3 días hábiles."
success: "Tu pago se realizó al método de pago seleccionado."
redirection_text:
redirecting: "Redirigiendo..."
redirecting_in: "Redirigiendo en"
seconds: "segundos..."
text:
failed: "Fallo en el Pago"
processing: "Pago en Proceso"
success: "Pago Exitoso"
time:
am: "AM"
pm: "PM"
months:
january: "Enero"
february: "Febrero"
march: "Marzo"
april: "Abril"
may: "Mayo"
june: "Junio"
july: "Julio"
august: "Agosto"
september: "Septiembre"
october: "Octubre"
november: "Noviembre"
december: "Diciembre"
| 311 | 1,080 |
hyperswitch | crates/router/locales/pl.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Nie masz uprawnień do wyświetlania tej treści"
title: "Linki do wypłat"
status:
title: "Status wypłaty"
info:
ref_id: "ID referencyjny"
error_code: "Kod błędu"
error_message: "Komunikat o błędzie"
message:
failed: "Nie udało się przetworzyć Twojej wypłaty. Skontaktuj się z dostawcą w celu uzyskania szczegółowych informacji."
processing: "Twoja wypłata powinna zostać przetworzona w ciągu 2-3 dni roboczych."
success: "Twoja wypłata została zrealizowana metodą płatności, którą wybrałeś."
redirection_text:
redirecting: "Przekierowywanie..."
redirecting_in: "Przekierowywanie za"
seconds: "sekund..."
text:
failed: "Wypłata Nieudana"
processing: "Wypłata w Trakcie"
success: "Wypłata Udała się"
time:
am: "AM"
pm: "PM"
months:
january: "Styczeń"
february: "Luty"
march: "Marzec"
april: "Kwiecień"
may: "Maj"
june: "Czerwiec"
july: "Lipiec"
august: "Sierpień"
september: "Wrzesień"
october: "Październik"
november: "Listopad"
december: "Grudzień"
| 389 | 1,081 |
hyperswitch | crates/router/locales/ja.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "このコンテンツを見ることはできません"
title: "支払いリンク"
status:
title: "支払いステータス"
info:
ref_id: "参照ID"
error_code: "エラーコード"
error_message: "エラーメッセージ"
message:
failed: "支払いの処理に失敗しました。詳細については提供者に確認してください。"
processing: "支払いは2〜3営業日以内に処理される予定です。"
success: "支払いが選択した支払い方法に対して行われました。"
redirection_text:
redirecting: "リダイレクト中..."
redirecting_in: "リダイレクトまで"
seconds: "秒..."
text:
failed: "支払い失敗"
processing: "支払い処理中"
success: "支払い成功"
time:
am: "AM"
pm: "PM"
months:
january: "1月"
february: "2月"
march: "3月"
april: "4月"
may: "5月"
june: "6月"
july: "7月"
august: "8月"
september: "9月"
october: "10月"
november: "11月"
december: "12月"
| 322 | 1,082 |
hyperswitch | crates/router/locales/ar.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "لا يُسمح لك بمشاهدة هذا المحتوى"
title: "روابط الدفع"
status:
title: "حالة الدفع"
info:
ref_id: "معرف المرجع"
error_code: "رمز الخطأ"
error_message: "رسالة الخطأ"
message:
failed: "فشل في معالجة الدفع الخاص بك. يرجى التحقق مع مزود الخدمة للحصول على مزيد من التفاصيل."
processing: "يجب معالجة الدفع الخاص بك خلال 2-3 أيام عمل."
success: "تم تنفيذ الدفع إلى طريقة الدفع المختارة."
redirection_text:
redirecting: "جارٍ إعادة التوجيه..."
redirecting_in: "إعادة التوجيه خلال"
seconds: "ثوانٍ..."
text:
failed: "فشل الدفع"
processing: "الدفع قيد المعالجة"
success: "الدفع ناجح"
time:
am: "صباحا"
pm: "مساء"
months:
january: "يناير"
february: "فبراير"
march: "مارس"
april: "أبريل"
may: "مايو"
june: "يونيو"
july: "يوليو"
august: "أغسطس"
september: "سبتمبر"
october: "أكتوبر"
november: "نوفمبر"
december: "ديسمبر"
| 353 | 1,083 |
hyperswitch | crates/router/locales/nl.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Je bent niet toegestaan om deze inhoud te bekijken"
title: "Betalingslinks"
status:
title: "Betalingsstatus"
info:
ref_id: "Referentie-ID"
error_code: "Foutcode"
error_message: "Foutmelding"
message:
failed: "Het is niet gelukt om je betaling te verwerken. Controleer bij je aanbieder voor meer details."
processing: "Je betaling moet binnen 2-3 werkdagen worden verwerkt."
success: "Je betaling is uitgevoerd naar de geselecteerde betaalmethode."
redirection_text:
redirecting: "Doorverwijzen..."
redirecting_in: "Doorverwijzen in"
seconds: "seconden..."
text:
failed: "Betaling Mislukt"
processing: "Betaling in Behandeling"
success: "Betaling Succesvol"
time:
am: "AM"
pm: "PM"
months:
january: "Januari"
february: "Februari"
march: "Maart"
april: "April"
may: "Mei"
june: "Juni"
july: "Juli"
august: "Augustus"
september: "September"
october: "Oktober"
november: "November"
december: "December"
| 332 | 1,084 |
hyperswitch | crates/router/locales/it.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Non sei autorizzato a visualizzare questo contenuto"
title: "Link di Pagamento"
status:
title: "Stato del Pagamento"
info:
ref_id: "ID di Riferimento"
error_code: "Codice di Errore"
error_message: "Messaggio di Errore"
message:
failed: "Impossibile elaborare il tuo pagamento. Contatta il tuo fornitore per ulteriori dettagli."
processing: "Il tuo pagamento dovrebbe essere elaborato entro 2-3 giorni lavorativi."
success: "Il tuo pagamento è stato effettuato al metodo di pagamento selezionato."
redirection_text:
redirecting: "Reindirizzamento..."
redirecting_in: "Reindirizzamento tra"
seconds: "secondi..."
text:
failed: "Pagamento Fallito"
processing: "Pagamento in Corso"
success: "Pagamento Riuscito"
time:
am: "AM"
pm: "PM"
months:
january: "Gennaio"
february: "Febbraio"
march: "Marzo"
april: "Aprile"
may: "Maggio"
june: "Giugno"
july: "Luglio"
august: "Agosto"
september: "Settembre"
october: "Ottobre"
november: "Novembre"
december: "Dicembre"
| 342 | 1,085 |
hyperswitch | crates/router/locales/he.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "אינך מורשה לצפות בתוכן זה"
title: "קישורי תשלום"
status:
title: "סטטוס תשלום"
info:
ref_id: "מספר הפניה"
error_code: "קוד שגיאה"
error_message: "הודעת שגיאה"
message:
failed: "נכשל בעיבוד התשלום שלך. אנא בדוק עם הספק שלך למידע נוסף."
processing: "התשלום שלך צריך להיות מעובד בתוך 2-3 ימי עסקים."
success: "התשלום שלך בוצע לשיטת התשלום שנבחרה."
redirection_text:
redirecting: "מופנה..."
redirecting_in: "מופנה בעוד"
seconds: "שניות..."
text:
failed: "תשלום נכשל"
processing: "תשלום בתהליך"
success: "תשלום הצליח"
time:
am: "בבוקר"
pm: "בערב"
months:
january: "ינואר"
february: "פברואר"
march: "מרץ"
april: "אפריל"
may: "מאי"
june: "יוני"
july: "יולי"
august: "אוגוסט"
september: "ספטמבר"
october: "אוקטובר"
november: "נובמבר"
december: "דצמבר"
| 317 | 1,086 |
hyperswitch | crates/router/locales/ru.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Вам не разрешено просматривать этот контент"
title: "Ссылки на выплаты"
status:
title: "Статус выплаты"
info:
ref_id: "ID ссылки"
error_code: "Код ошибки"
error_message: "Сообщение об ошибке"
message:
failed: "Не удалось обработать вашу выплату. Пожалуйста, проверьте у вашего поставщика более подробную информацию."
processing: "Ваша выплата должна быть обработана в течение 2-3 рабочих дней."
success: "Ваша выплата была произведена на выбранный метод оплаты."
redirection_text:
redirecting: "Перенаправление..."
redirecting_in: "Перенаправление через"
seconds: "секунд..."
text:
failed: "Выплата не удалась"
processing: "Выплата в процессе"
success: "Выплата успешна"
time:
am: "AM"
pm: "PM"
months:
january: "Январь"
february: "Февраль"
march: "Март"
april: "Апрель"
may: "Май"
june: "Июнь"
july: "Июль"
august: "Август"
september: "Сентябрь"
october: "Октябрь"
november: "Ноябрь"
december: "Декабрь"
| 375 | 1,087 |
hyperswitch | crates/router/locales/sv.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Du har inte tillåtelse att visa detta innehåll"
title: "Utbetalningslänkar"
status:
title: "Utbetalningsstatus"
info:
ref_id: "Referens-ID"
error_code: "Felkod"
error_message: "Felmeddelande"
message:
failed: "Det gick inte att behandla din utbetalning. Kontrollera med din leverantör för mer information."
processing: "Din utbetalning bör behandlas inom 2-3 arbetsdagar."
success: "Din utbetalning har genomförts till vald betalningsmetod."
redirection_text:
redirecting: "Omdirigerar..."
redirecting_in: "Omdirigerar om"
seconds: "sekunder..."
text:
failed: "Utbetalning Misslyckades"
processing: "Utbetalning Under Behandling"
success: "Utbetalning Lyckad"
time:
am: "AM"
pm: "PM"
months:
january: "Januari"
february: "Februari"
march: "Mars"
april: "April"
may: "Maj"
june: "Juni"
july: "Juli"
august: "Augusti"
september: "September"
october: "Oktober"
november: "November"
december: "December"
| 344 | 1,088 |
hyperswitch | crates/router/locales/en-GB.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "You are not allowed to view this content"
title: "Payout Links"
status:
title: "Payout Status"
info:
ref_id: "Ref Id"
error_code: "Error Code"
error_message: "Error Message"
message:
failed: "Failed to process your payout. Please check with your provider for more details."
processing: "Your payout should be processed within 2-3 business days."
success: "Your payout was made to selected payment method."
redirection_text:
redirecting: "Redirecting..."
redirecting_in: "Redirecting in"
seconds: "seconds..."
text:
failed: "Payout Failed"
processing: "Payout Processing"
success: "Payout Successful"
time:
am: "AM"
pm: "PM"
months:
january: "January"
february: "February"
march: "March"
april: "April"
may: "May"
june: "June"
july: "July"
august: "August"
september: "September"
october: "October"
november: "November"
december: "December"
| 272 | 1,089 |
hyperswitch | crates/router/locales/fr-BE.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Vous n'êtes pas autorisé à voir ce contenu"
title: "Liens de paiement"
status:
title: "Statut du paiement"
info:
ref_id: "ID de référence"
error_code: "Code d'erreur"
error_message: "Message d'erreur"
message:
failed: "Échec du traitement de votre paiement. Veuillez vérifier auprès de votre fournisseur pour plus de détails."
processing: "Votre paiement devrait être traité dans les 2 à 3 jours ouvrables."
success: "Votre paiement a été effectué sur le mode de paiement sélectionné."
redirection_text:
redirecting: "Redirection..."
redirecting_in: "Redirection dans"
seconds: "secondes..."
text:
failed: "Échec du paiement"
processing: "Paiement en cours"
success: "Paiement réussi"
time:
am: "AM"
pm: "PM"
months:
january: "Janvier"
february: "Février"
march: "Mars"
april: "Avril"
may: "Mai"
june: "Juin"
july: "Juillet"
august: "Août"
september: "Septembre"
october: "Octobre"
november: "Novembre"
december: "Décembre"
| 329 | 1,090 |
hyperswitch | crates/router/locales/en.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "You are not allowed to view this content"
title: "Payout Links"
status:
title: "Payout Status"
info:
ref_id: "Reference Id"
error_code: "Error Code"
error_message: "Error Message"
message:
failed: "Failed to process your payout. Please check with your provider for more details."
processing: "Your payout should be processed within 2-3 business days."
success: "Your payout was made to selected payment method."
redirection_text:
redirecting: "Redirecting ..."
redirecting_in: "Redirecting in"
seconds: "seconds ..."
text:
failed: "Payout Failed"
processing: "Payout Processing"
success: "Payout Successful"
time:
am: "AM"
pm: "PM"
months:
january: "January"
february: "February"
march: "March"
april: "April"
may: "May"
june: "June"
july: "July"
august: "August"
september: "September"
october: "October"
november: "November"
december: "December" | 272 | 1,091 |
hyperswitch | crates/router/locales/fr.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Vous n'êtes pas autorisé à voir ce contenu"
title: "Liens de Paiement"
status:
title: "Statut de Paiement"
info:
ref_id: "Id de Réf"
error_code: "Code d'Erreur"
error_message: "Message d'Erreur"
message:
failed: "Échec du traitement de votre paiement. Veuillez vérifier auprès de votre fournisseur pour plus de détails."
processing: "Votre paiement devrait être traité dans les 2 à 3 jours ouvrables."
success: "Votre paiement a été effectué sur le mode de paiement sélectionné."
redirection_text:
redirecting: "Redirection ..."
redirecting_in: "Redirection dans"
seconds: "secondes ..."
text:
failed: "Échec du Paiement"
processing: "Traitement du Paiement"
success: "Paiement Réussi"
time:
am: "AM"
pm: "PM"
months:
january: "Janvier"
february: "Février"
march: "Mars"
april: "Avril"
may: "Mai"
june: "Juin"
july: "Juillet"
august: "Août"
september: "Septembre"
october: "Octobre"
november: "Novembre"
december: "Décembre"
| 332 | 1,092 |
hyperswitch | crates/router/locales/pt.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "Você não tem permissão para visualizar este conteúdo"
title: "Links de Pagamento"
status:
title: "Status do Pagamento"
info:
ref_id: "ID de Referência"
error_code: "Código de Erro"
error_message: "Mensagem de Erro"
message:
failed: "Falha ao processar seu pagamento. Verifique com seu provedor para mais detalhes."
processing: "Seu pagamento deve ser processado em 2-3 dias úteis."
success: "Seu pagamento foi realizado no método de pagamento selecionado."
redirection_text:
redirecting: "Redirecionando..."
redirecting_in: "Redirecionando em"
seconds: "segundos..."
text:
failed: "Falha no Pagamento"
processing: "Pagamento em Processamento"
success: "Pagamento Bem-Sucedido"
time:
am: "AM"
pm: "PM"
months:
january: "Janeiro"
february: "Fevereiro"
march: "Março"
april: "Abril"
may: "Maio"
june: "Junho"
july: "Julho"
august: "Agosto"
september: "Setembro"
october: "Outubro"
november: "Novembro"
december: "Dezembro"
| 324 | 1,093 |
hyperswitch | crates/router/locales/ca.yml | .yml | _version: 1
payout_link:
initiate:
not_allowed: "No tens permís per veure aquest contingut"
title: "Enllaços de Pagament"
status:
title: "Estat del Pagament"
info:
ref_id: "ID de Referència"
error_code: "Codi d'Error"
error_message: "Missatge d'Error"
message:
failed: "No s'ha pogut processar el teu pagament. Si us plau, comprova-ho amb el teu proveïdor per obtenir més detalls."
processing: "El teu pagament hauria de ser processat en 2-3 dies hàbils."
success: "El teu pagament s'ha realitzat al mètode de pagament seleccionat."
redirection_text:
redirecting: "Redirigint..."
redirecting_in: "Redirigint en"
seconds: "segons..."
text:
failed: "Falla en el Pagament"
processing: "Pagament en Procés"
success: "Pagament Exitos"
time:
am: "AM"
pm: "PM"
months:
january: "Gener"
february: "Febrer"
march: "Març"
april: "Abril"
may: "Maig"
june: "Juny"
july: "Juliol"
august: "Agost"
september: "Setembre"
october: "Octubre"
november: "Novembre"
december: "Desembre"
| 361 | 1,094 |
hyperswitch | crates/router/tests/integration_demo.rs | .rs | #![allow(clippy::unwrap_used)]
mod utils;
use masking::PeekInterface;
use test_utils::connector_auth::ConnectorAuthentication;
use utils::{mk_service, ApiKey, AppClient, MerchantId, PaymentId, Status};
/// Example of unit test
/// Kind of test: output-based testing
/// 1) Create Merchant account
#[actix_web::test]
async fn create_merchant_account() {
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
let admin_client = client.admin("test_admin");
let expected = "merchant_12345";
let expected_merchant_id_type =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_12345"))
.unwrap();
let hlist_pat![merchant_id, _api_key]: HList![MerchantId, ApiKey] = admin_client
.create_merchant_account(&server, expected.to_owned())
.await;
assert_eq!(expected_merchant_id_type, *merchant_id);
}
/// Example of unit test
/// Kind of test: communication-based testing
/// ```pseudocode
/// mk_service =
/// app_state <- AppState(StorageImpl::Mock) // Instantiate a mock database to simulate real world SQL database.
/// actix_web::test::init_service(<..>) // Initialize service from application builder instance .
/// ```
/// ### Tests with mocks are typically structured like so:
/// 1) create mock objects and specify what values they return
/// 2) run code under test, passing mock objects to it
/// 3) assert mocks were called the expected number of times, with the expected arguments
/// ```
/// fn show_users(get_users: impl FnOnce() -> Vec<&'static str>) -> String {
/// get_users().join(", ")
/// }
/// // GIVEN[1]:
/// let get_users = || vec!["Andrey", "Alisa"];
/// // WHEN[2]:
/// let list_users = show_users(get_users);
/// // THEN[3]:
/// assert_eq!(list_users, "Andrey, Alisa");
/// ```
/// ### Test case
/// 1) Create Merchant account (Get the API key)
/// 2) Create a connector
/// 3) Create a payment for 100 USD
/// 4) Confirm a payment (let it get processed through Stripe)
/// 5) Refund for 50USD success
/// 6) Another refund for 50USD success
///
/// ### Useful resources
/// * <https://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters>
/// * <https://www.parsonsmatt.org/2017/07/27/inverted_mocking.html>
/// * <https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html>
#[actix_web::test]
async fn partial_refund() {
let authentication = ConnectorAuthentication::new();
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
let admin_client = client.admin("test_admin");
let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] =
admin_client.create_merchant_account(&server, None).await;
let _connector: serde_json::Value = admin_client
.create_connector(
&server,
&merchant_id,
"stripe",
authentication.checkout.unwrap().api_key.peek(),
)
.await;
let user_client = client.user(&api_key);
let hlist_pat![payment_id]: HList![PaymentId] =
user_client.create_payment(&server, 100, 100).await;
let hlist_pat![status]: HList![Status] =
user_client.create_refund(&server, &payment_id, 50).await;
assert_eq!(&*status, "pending");
let hlist_pat![status]: HList![Status] =
user_client.create_refund(&server, &payment_id, 50).await;
assert_eq!(&*status, "pending");
}
/// Example of unit test
/// Kind of test: communication-based testing
/// ```pseudocode
/// mk_service =
/// app_state <- AppState(StorageImpl::Mock) // Instantiate a mock database to simulate real world SQL database.
/// actix_web::test::init_service(<..>) // Initialize service from application builder instance .
/// ```
/// ### Tests with mocks are typically structured like so:
/// 1) create mock objects and specify what values they return
/// 2) run code under test, passing mock objects to it
/// 3) assert mocks were called the expected number of times, with the expected arguments
/// ```
/// fn show_users(get_users: impl FnOnce() -> Vec<&'static str>) -> String {
/// get_users().join(", ")
/// }
/// // GIVEN[1]:
/// let get_users = || vec!["Andrey", "Alisa"];
/// // WHEN[2]:
/// let list_users = show_users(get_users);
/// // THEN[3]:
/// assert_eq!(list_users, "Andrey, Alisa");
/// ```
/// Test case
/// 1) Create a payment for 100 USD
/// 2) Confirm a payment (let it get processed through Stripe)
/// 3) Refund for 50USD successfully
/// 4) Try another refund for 100USD
/// 5) Get an error for second refund
///
/// ### Useful resources
/// * <https://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters>
/// * <https://www.parsonsmatt.org/2017/07/27/inverted_mocking.html>
/// * <https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html>
#[actix_web::test]
async fn exceed_refund() {
let authentication = ConnectorAuthentication::new();
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
let admin_client = client.admin("test_admin");
let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] =
admin_client.create_merchant_account(&server, None).await;
let _connector: serde_json::Value = admin_client
.create_connector(
&server,
&merchant_id,
"stripe",
authentication.checkout.unwrap().api_key.peek(),
)
.await;
let user_client = client.user(&api_key);
let hlist_pat![payment_id]: HList![PaymentId] =
user_client.create_payment(&server, 100, 100).await;
let hlist_pat![status]: HList![Status] =
user_client.create_refund(&server, &payment_id, 50).await;
assert_eq!(&*status, "pending");
let message: serde_json::Value = user_client.create_refund(&server, &payment_id, 100).await;
assert_eq!(
message.get("error").unwrap().get("message").unwrap(),
"The refund amount exceeds the amount captured."
);
}
| 1,588 | 1,095 |
hyperswitch | crates/router/tests/cache.rs | .rs | #![allow(clippy::unwrap_used, clippy::print_stdout)]
use std::sync::Arc;
use router::{configs::settings::Settings, routes, services};
use storage_impl::redis::cache::{self, CacheKey};
mod utils;
#[actix_web::test]
async fn invalidate_existing_cache_success() {
// Arrange
Box::pin(utils::setup()).await;
let (tx, _) = tokio::sync::oneshot::channel();
let app_state = Box::pin(routes::AppState::new(
Settings::default(),
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let cache_key = "cacheKey".to_string();
let cache_key_value = "val".to_string();
let _ = state
.store
.get_redis_conn()
.unwrap()
.set_key(&cache_key.clone().into(), cache_key_value.clone())
.await;
let api_key = ("api-key", "test_admin");
let client = awc::Client::default();
cache::CONFIG_CACHE
.push(
CacheKey {
key: cache_key.clone(),
prefix: String::default(),
},
cache_key_value.clone(),
)
.await;
cache::ACCOUNTS_CACHE
.push(
CacheKey {
key: cache_key.clone(),
prefix: String::default(),
},
cache_key_value.clone(),
)
.await;
// Act
let mut response = client
.post(format!(
"http://127.0.0.1:8080/cache/invalidate/{cache_key}"
))
.insert_header(api_key)
.send()
.await
.unwrap();
// Assert
let response_body = response.body().await;
println!("invalidate Cache: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
assert!(cache::CONFIG_CACHE
.get_val::<String>(CacheKey {
key: cache_key.clone(),
prefix: String::default()
})
.await
.is_none());
assert!(cache::ACCOUNTS_CACHE
.get_val::<String>(CacheKey {
key: cache_key,
prefix: String::default()
})
.await
.is_none());
}
#[actix_web::test]
async fn invalidate_non_existing_cache_success() {
// Arrange
Box::pin(utils::setup()).await;
let cache_key = "cacheKey".to_string();
let api_key = ("api-key", "test_admin");
let client = awc::Client::default();
// Act
let mut response = client
.post(format!(
"http://127.0.0.1:8080/cache/invalidate/{cache_key}"
))
.insert_header(api_key)
.send()
.await
.unwrap();
// Assert
let response_body = response.body().await;
println!("invalidate Cache: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::NOT_FOUND);
}
| 728 | 1,096 |
hyperswitch | crates/router/tests/health_check.rs | .rs | mod utils;
use utils::{mk_service, AppClient};
#[actix_web::test]
async fn health_check() {
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
assert_eq!(client.health(&server).await, "health is good");
}
| 64 | 1,097 |
hyperswitch | crates/router/tests/payments.rs | .rs | #![allow(
clippy::expect_used,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::print_stdout
)]
mod utils;
use std::{borrow::Cow, sync::Arc};
use common_utils::{id_type, types::MinorUnit};
use router::{
configs,
core::payments,
db::StorageImpl,
routes, services,
types::{
self,
api::{self, enums as api_enums},
},
};
use time::macros::datetime;
use tokio::sync::oneshot;
use uuid::Uuid;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has stripe as first choice
async fn payments_create_stripe() {
Box::pin(utils::setup()).await;
let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let request = serde_json::json!({
"payment_id" : payment_id,
"merchant_id" : "jarnura",
"amount" : 1000,
"currency" : "USD",
"amount_to_capture" : 1000,
"confirm" : true,
"customer" : "test_customer",
"customer_email" : "test@gmail.com",
"customer_name" : "Test",
"description" : "stripe",
"return_url" : "https://juspay.in/",
"payment_method_data" : {"card" : {"card_number":"4242424242424242","card_exp_month":"12","card_exp_year":"29","card_holder_name":"JohnDoe","card_cvc":"123"}},
"payment_method" : "card",
"statement_descriptor_name" : "Test Merchant",
"statement_descriptor_suffix" : "US"
});
let refund_req = serde_json::json!({
"amount" : 1000,
"currency" : "USD",
"refund_id" : "refund_123",
"payment_id" : payment_id,
"merchant_id" : "jarnura",
});
let client = awc::Client::default();
let mut create_response = client
.post("http://127.0.0.1:8080/payments/create")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let create_response_body = create_response.body().await;
println!("{create_response:?} : {create_response_body:?}");
assert_eq!(create_response.status(), awc::http::StatusCode::OK);
let mut retrieve_response = client
.get("http://127.0.0.1:8080/payments/retrieve")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let retrieve_response_body = retrieve_response.body().await;
println!("{retrieve_response:?} =:= {retrieve_response_body:?}");
assert_eq!(retrieve_response.status(), awc::http::StatusCode::OK);
let mut refund_response = client
.post("http://127.0.0.1:8080/refunds/create")
.insert_header(api_key)
.send_json(&refund_req)
.await
.unwrap();
let refund_response_body = refund_response.body().await;
println!("{refund_response:?} =:= {refund_response_body:?}");
assert_eq!(refund_response.status(), awc::http::StatusCode::OK);
}
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has adyen as first choice
async fn payments_create_adyen() {
Box::pin(utils::setup()).await;
let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "321");
let request = serde_json::json!({
"payment_id" : payment_id,
"merchant_id" : "jarnura",
"amount" : 1000,
"currency" : "USD",
"amount_to_capture" : 1000,
"confirm" : true,
"customer" : "test_customer",
"customer_email" : "test@gmail.com",
"customer_name" : "Test",
"description" : "adyen",
"return_url" : "https://juspay.in/",
"payment_method_data" : {"card" : {"card_number":"5555 3412 4444 1115","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"JohnDoe","card_cvc":"737"}},
"payment_method" : "card",
"statement_descriptor_name" : "Test Merchant",
"statement_descriptor_suffix" : "US"
});
let refund_req = serde_json::json!({
"amount" : 1000,
"currency" : "USD",
"refund_id" : "refund_123",
"payment_id" : payment_id,
"merchant_id" : "jarnura",
});
let client = awc::Client::default();
let mut create_response = client
.post("http://127.0.0.1:8080/payments/create")
.insert_header(api_key) //API Key must have adyen as first choice
.send_json(&request)
.await
.unwrap();
let create_response_body = create_response.body().await;
println!("{create_response:?} : {create_response_body:?}");
assert_eq!(create_response.status(), awc::http::StatusCode::OK);
let mut retrieve_response = client
.get("http://127.0.0.1:8080/payments/retrieve")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let retrieve_response_body = retrieve_response.body().await;
println!("{retrieve_response:?} =:= {retrieve_response_body:?}");
assert_eq!(retrieve_response.status(), awc::http::StatusCode::OK);
let mut refund_response = client
.post("http://127.0.0.1:8080/refunds/create")
.insert_header(api_key)
.send_json(&refund_req)
.await
.unwrap();
let refund_response_body = refund_response.body().await;
println!("{refund_response:?} =:= {refund_response_body:?}");
assert_eq!(refund_response.status(), awc::http::StatusCode::OK);
}
#[actix_web::test]
// verify the API-KEY/merchant id has stripe as first choice
#[ignore]
async fn payments_create_fail() {
Box::pin(utils::setup()).await;
let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let invalid_request = serde_json::json!({
"description" : "stripe",
});
let request = serde_json::json!({
"payment_id" : payment_id,
"merchant_id" : "jarnura",
"amount" : 1000,
"currency" : "USD",
"amount_to_capture" : 1000,
"confirm" : true,
"customer" : "test_customer",
"customer_email" : "test@gmail.com",
"customer_name" : "Test",
"description" : "adyen",
"return_url" : "https://juspay.in/",
"payment_method_data" : {"card" : {"card_number":"5555 3412 4444 1115","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"JohnDoe","card_cvc":"737"}},
"payment_method" : "card",
"statement_descriptor_name" : "Test Merchant",
"statement_descriptor_suffix" : "US"
});
let client = awc::Client::default();
let mut invalid_response = client
.post("http://127.0.0.1:8080/payments/create")
.insert_header(api_key)
.send_json(&invalid_request)
.await
.unwrap();
let invalid_response_body = invalid_response.body().await;
println!("{invalid_response:?} : {invalid_response_body:?}");
assert_eq!(
invalid_response.status(),
awc::http::StatusCode::BAD_REQUEST
);
let mut api_key_response = client
.get("http://127.0.0.1:8080/payments/retrieve")
// .insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let api_key_response_body = api_key_response.body().await;
println!("{api_key_response:?} =:= {api_key_response_body:?}");
assert_eq!(
api_key_response.status(),
awc::http::StatusCode::UNAUTHORIZED
);
}
#[actix_web::test]
#[ignore]
async fn payments_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let _post_endpoints = ["123/update", "123/confirm", "cancel"];
let get_endpoints = vec!["list"];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/payments/{endpoint}"))
.insert_header(("API-KEY", "MySecretApiKey"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
// for endpoint in post_endpoints {
// response = client
// .post(format!("http://127.0.0.1:8080/payments/{}", endpoint))
// .send()
// .await
// .unwrap();
// response_body = response.body().await;
// println!("{} =:= {:?} : {:?}", endpoint, response, response_body);
// assert_eq!(response.status(), awc::http::StatusCode::OK);
// }
}
#[test]
fn connector_list() {
let connector_list = types::ConnectorsList {
connectors: vec![String::from("stripe"), "adyen".to_string()],
};
let json = serde_json::to_string(&connector_list).unwrap();
println!("{}", &json);
let newlist: types::ConnectorsList = serde_json::from_str(&json).unwrap();
println!("{newlist:#?}");
assert_eq!(true, true);
}
#[cfg(feature = "v1")]
#[actix_rt::test]
#[ignore] // AWS
async fn payments_create_core() {
use configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
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
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 11:12)),
confirm: Some(true),
customer_id: None,
email: None,
name: None,
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OnSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "4242424242424242".to_string().try_into().unwrap(),
card_exp_month: "10".to_string().into(),
card_exp_year: "35".to_string().into(),
card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Hyperswtich".to_string()),
statement_descriptor_suffix: Some("Hyperswitch".to_string()),
..Default::default()
};
let expected_response = api::PaymentsResponse {
payment_id,
status: api_enums::IntentStatus::Succeeded,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
ephemeral_key: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
order_tax_amount: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
merchant_account,
None,
key_store,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
None,
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
// #[actix_rt::test]
// async fn payments_start_core_stripe_redirect() {
// use configs::settings::Settings;
// let conf = Settings::new().expect("invalid settings");
// let state = routes::AppState {
// flow_name: String::from("default"),
// pg_conn: connection::pg_connection_read(&conf),
// redis_conn: connection::redis_connection(&conf).await,
// };
// let customer_id = format!("cust_{}", Uuid::new_v4());
// let merchant_id = "jarnura".to_string();
// let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();
// let customer_data = api::CreateCustomerRequest {
// customer_id: customer_id.clone(),
// merchant_id: merchant_id.clone(),
// ..api::CreateCustomerRequest::default()
// };
// let _customer = customer_data.insert(&state.pg_conn).unwrap();
// let merchant_account = services::authenticate(&state, "MySecretApiKey").unwrap();
// let payment_attempt = storage::PaymentAttempt::find_by_payment_id_merchant_id(
// &state.pg_conn,
// &payment_id,
// &merchant_id,
// )
// .unwrap();
// let payment_intent = storage::PaymentIntent::find_by_payment_id_merchant_id(
// &state.pg_conn,
// &payment_id,
// &merchant_id,
// )
// .unwrap();
// let payment_intent_update = storage::PaymentIntentUpdate::ReturnUrlUpdate {
// return_url: "http://example.com/payments".to_string(),
// status: None,
// };
// payment_intent
// .update(&state.pg_conn, payment_intent_update)
// .unwrap();
// let expected_response = services::ApplicationResponse::Form(services::RedirectForm {
// url: "http://example.com/payments".to_string(),
// method: services::Method::Post,
// form_fields: HashMap::from([("payment_id".to_string(), payment_id.clone())]),
// });
// let actual_response = payments_start_core(
// &state,
// merchant_account,
// api::PaymentsStartRequest {
// payment_id,
// merchant_id,
// txn_id: payment_attempt.txn_id.to_owned(),
// },
// )
// .await
// .unwrap();
// assert_eq!(expected_response, actual_response);
// }
#[cfg(feature = "v1")]
#[actix_rt::test]
#[ignore]
async fn payments_create_core_adyen_no_redirect() {
use crate::configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let customer_id = format!("cust_{}", Uuid::new_v4());
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
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
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 10:11:12)),
confirm: Some(true),
customer_id: Some(id_type::CustomerId::try_from(Cow::from(customer_id)).unwrap()),
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OnSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(),
card_exp_month: "03".to_string().into(),
card_exp_year: "2030".to_string().into(),
card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "737".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Juspay".to_string()),
statement_descriptor_suffix: Some("Router".to_string()),
..Default::default()
};
let expected_response = services::ApplicationResponse::JsonWithHeaders((
api::PaymentsResponse {
payment_id: payment_id.clone(),
status: api_enums::IntentStatus::Processing,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
ephemeral_key: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
order_tax_amount: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
},
vec![],
));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
merchant_account,
None,
key_store,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
None,
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
| 6,224 | 1,098 |
hyperswitch | crates/router/tests/webhooks.rs | .rs | // use std::sync;
// use router::{configs::settings, connection, core::webhooks, types::api};
// mod utils;
// fn get_config() -> settings::Settings {
// settings::Settings::new().expect("Settings")
// }
// struct TestApp {
// redis_conn: connection::RedisPool,
// }
// impl TestApp {
// async fn init() -> Self {
// utils::setup().await;
// let conf = get_config();
// Self {
// redis_conn: sync::Arc::new(connection::redis_connection(&conf.redis).await),
// }
// }
// }
// #[actix_web::test]
// async fn test_webhook_config_lookup() {
// let app = TestApp::init().await;
// let timestamp = router::utils::date_time::now();
// let merchant_id = format!("merchant_{timestamp}");
// let connector_id = "stripe";
// let config = serde_json::json!(["payment_intent_success"]);
// let lookup_res = webhooks::utils::lookup_webhook_event(
// connector_id,
// &merchant_id,
// &api::IncomingWebhookEvent::PaymentIntentSuccess,
// sync::Arc::clone(&app.redis_conn),
// )
// .await;
// assert!(lookup_res);
// app.redis_conn
// .serialize_and_set_key(&format!("whconf_{merchant_id}_{connector_id}"), &config)
// .await
// .expect("Save merchant webhook config");
// let lookup_res = webhooks::utils::lookup_webhook_event(
// connector_id,
// &merchant_id,
// &api::IncomingWebhookEvent::PaymentIntentSuccess,
// sync::Arc::clone(&app.redis_conn),
// )
// .await;
// assert!(lookup_res);
// }
| 394 | 1,099 |
hyperswitch | crates/router/tests/utils.rs | .rs | #![allow(
dead_code,
clippy::expect_used,
clippy::missing_panics_doc,
clippy::unwrap_used
)]
use actix_http::{body::MessageBody, Request};
use actix_web::{
dev::{Service, ServiceResponse},
test::{call_and_read_body_json, TestRequest},
};
use derive_deref::Deref;
use router::{configs::settings::Settings, routes::AppState, services};
use router_env::tracing::Instrument;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::{json, Value};
use tokio::sync::{oneshot, OnceCell};
static SERVER: OnceCell<bool> = OnceCell::const_new();
async fn spawn_server() -> bool {
let conf = Settings::new().expect("invalid settings");
let server = Box::pin(router::start_server(conf))
.await
.expect("failed to create server");
let _server = tokio::spawn(server.in_current_span());
true
}
pub async fn setup() {
Box::pin(SERVER.get_or_init(spawn_server)).await;
}
const STRIPE_MOCK: &str = "http://localhost:12111/";
async fn stripemock() -> Option<String> {
// not working: https://github.com/stripe/stripe-mock/issues/231
None
}
pub async fn mk_service(
) -> impl Service<Request, Response = ServiceResponse<impl MessageBody>, Error = actix_web::Error> {
let mut conf = Settings::new().unwrap();
let request_body_limit = conf.server.request_body_limit;
if let Some(url) = stripemock().await {
conf.connectors.stripe.base_url = url;
}
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(AppState::with_storage(
conf,
router::db::StorageImpl::Mock,
tx,
Box::new(services::MockApiClient),
))
.await;
actix_web::test::init_service(router::mk_app(app_state, request_body_limit)).await
}
pub struct Guest;
pub struct Admin {
authkey: String,
}
pub struct User {
authkey: String,
}
#[allow(dead_code)]
pub struct AppClient<T> {
state: T,
}
impl AppClient<Guest> {
pub fn guest() -> Self {
Self { state: Guest }
}
}
impl AppClient<Admin> {
pub async fn create_merchant_account<T: DeserializeOwned, S, B>(
&self,
app: &S,
merchant_id: impl Into<Option<String>>,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri("/accounts")
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_merchant_account(merchant_id.into()))
.to_request();
call_and_read_body_json(app, request).await
}
pub async fn create_connector<T: DeserializeOwned, S, B>(
&self,
app: &S,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
api_key: &str,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri(&format!(
"/account/{}/connectors",
merchant_id.get_string_repr()
))
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_connector(connector_name, api_key))
.to_request();
call_and_read_body_json(app, request).await
}
}
impl AppClient<User> {
pub async fn create_payment<T: DeserializeOwned, S, B>(
&self,
app: &S,
amount: i64,
amount_to_capture: i32,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri("/payments")
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_payment(amount, amount_to_capture))
.to_request();
call_and_read_body_json(app, request).await
}
pub async fn create_refund<T: DeserializeOwned, S, B>(
&self,
app: &S,
payment_id: &common_utils::id_type::PaymentId,
amount: usize,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri("/refunds")
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_refund(payment_id, amount))
.to_request();
call_and_read_body_json(app, request).await
}
}
impl<T> AppClient<T> {
pub fn admin(&self, authkey: &str) -> AppClient<Admin> {
AppClient {
state: Admin {
authkey: authkey.to_string(),
},
}
}
pub fn user(&self, authkey: &str) -> AppClient<User> {
AppClient {
state: User {
authkey: authkey.to_string(),
},
}
}
pub async fn health<S, B>(&self, app: &S) -> String
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::get().uri("/health").to_request();
let bytes = actix_web::test::call_and_read_body(app, request).await;
String::from_utf8(bytes.to_vec()).unwrap()
}
}
fn mk_merchant_account(merchant_id: Option<String>) -> Value {
let merchant_id = merchant_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
json!({
"merchant_id": merchant_id,
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "Juspay Router",
"line2": "Koramangala",
"line3": "Stallion",
"city": "Bangalore",
"state": "Karnataka",
"zip": "560095",
"country": "IN"
}
},
"return_url": "www.example.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"routing_algorithm": {
"type": "single",
"data": "stripe"
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
})
}
fn mk_payment(amount: i64, amount_to_capture: i32) -> Value {
json!({
"amount": amount,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-10-10T10:11:12Z",
"amount_to_capture": amount_to_capture,
"customer_id": "cus_udst2tfldj6upmye2reztkmm4i",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "Hyperswitch",
"statement_descriptor_suffix": "Hyperswitch",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
})
}
fn mk_connector(connector_name: &str, api_key: &str) -> Value {
json!({
"connector_type": "fiz_operations",
"connector_name": connector_name,
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": api_key,
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "wallet",
"payment_method_types": [
"upi_collect",
"upi_intent"
],
"payment_method_issuers": [
"labore magna ipsum",
"aute"
],
"payment_schemes": [
"Discover",
"Discover"
],
"accepted_currencies": [
"AED",
"AED"
],
"accepted_countries": [
"in",
"us"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
],
"metadata": {
"city": "NY",
"unit": "245"
}
})
}
fn _mk_payment_confirm() -> Value {
json!({
"return_url": "http://example.com/payments",
"setup_future_usage": "on_session",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"shipping": {},
"billing": {}
})
}
fn mk_refund(payment_id: &common_utils::id_type::PaymentId, amount: usize) -> Value {
let timestamp = common_utils::date_time::now().to_string();
json!({
"payment_id": payment_id,
"refund_id": timestamp.get(23..),
"amount": amount,
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
})
}
pub struct HNil;
impl<'de> Deserialize<'de> for HNil {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(serde::de::IgnoredAny)?;
Ok(Self)
}
}
#[derive(Deserialize)]
pub struct HCons<H, T> {
#[serde(flatten)]
pub head: H,
#[serde(flatten)]
pub tail: T,
}
#[macro_export]
macro_rules! HList {
() => { $crate::utils::HNil };
($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> };
}
#[macro_export]
macro_rules! hlist_pat {
() => { $crate::utils::HNil };
($head:pat $(, $rest:pat)* $(,)?) => { $crate::utils::HCons { head: $head, tail: hlist_pat!($($rest),*) } };
}
#[derive(Deserialize, Deref)]
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Deserialize, Deref)]
pub struct ApiKey {
api_key: String,
}
#[derive(Deserialize)]
pub struct Error {
pub message: Message,
}
#[derive(Deserialize, Deref)]
pub struct Message {
message: String,
}
#[derive(Deserialize, Deref)]
pub struct PaymentId {
payment_id: common_utils::id_type::PaymentId,
}
#[derive(Deserialize, Deref)]
pub struct Status {
status: String,
}
| 2,966 | 1,100 |
hyperswitch | crates/router/tests/customers.rs | .rs | #![allow(clippy::unwrap_used, clippy::print_stdout)]
mod utils;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has stripe as first choice
async fn customer_success() {
Box::pin(utils::setup()).await;
let customer_id = format!("customer_{}", uuid::Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let name = "Doe";
let new_name = "new Doe";
let request = serde_json::json!({
"customer_id" : customer_id,
"name" : name,
});
let update_request = serde_json::json!({
"name" : new_name,
});
let client = awc::Client::default();
let mut response;
let mut response_body;
// create customer
response = client
.post("http://127.0.0.1:8080/customers")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("customer-create: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
// retrieve customer
response = client
.get(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("customer-retrieve: {response:?} =:= {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
// update customer
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&update_request)
.await
.unwrap();
response_body = response.body().await;
println!("customer-update: {response:?} =:= {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
// delete customer
response = client
.delete(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("customer-delete : {response:?} =:= {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has stripe as first choice
async fn customer_failure() {
Box::pin(utils::setup()).await;
let customer_id = format!("customer_{}", uuid::Uuid::new_v4());
let api_key = ("api-key", "MySecretApiKey");
let mut request = serde_json::json!({
"email" : "abcd",
});
let client = awc::Client::default();
let mut response;
let mut response_body;
// insert the customer with invalid email when id not found
response = client
.post("http://127.0.0.1:8080/customers")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
// retrieve a customer with customer id which is not in DB
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::BAD_REQUEST);
// update customer id with customer id which is not in DB
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
// delete a customer with customer id which is not in DB
response = client
.delete(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::BAD_REQUEST);
// email validation for customer update
request = serde_json::json!({ "customer_id": customer_id });
response = client
.post("http://127.0.0.1:8080/customers")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
request = serde_json::json!({
"email": "abch"
});
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
// address validation
request = serde_json::json!({
"email": "abch"
});
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
}
| 1,533 | 1,101 |
hyperswitch | crates/router/tests/refunds.rs | .rs | #![allow(clippy::unwrap_used, clippy::print_stdout)]
use utils::{mk_service, AppClient};
mod utils;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
// verify the API-KEY/merchant id has stripe as first choice
async fn refund_create_fail_stripe() {
let app = Box::pin(mk_service()).await;
let client = AppClient::guest();
let user_client = client.user("321");
let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await;
assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section.");
}
#[actix_web::test]
// verify the API-KEY/merchant id has adyen as first choice
async fn refund_create_fail_adyen() {
let app = Box::pin(mk_service()).await;
let client = AppClient::guest();
let user_client = client.user("321");
let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await;
assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section.");
}
#[actix_web::test]
#[ignore]
async fn refunds_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let get_endpoints = vec!["list"];
let post_endpoints: Vec<&str> = vec![];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/refunds/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
for endpoint in post_endpoints {
response = client
.post(format!("http://127.0.0.1:8080/refunds/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
}
| 660 | 1,102 |
hyperswitch | crates/router/tests/payments2.rs | .rs | #![allow(
clippy::expect_used,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::print_stdout,
unused_imports
)]
mod utils;
use std::{borrow::Cow, sync::Arc};
use common_utils::{id_type, types::MinorUnit};
use router::{
core::payments,
db::StorageImpl,
types::api::{self, enums as api_enums},
*,
};
use time::macros::datetime;
use tokio::sync::oneshot;
use uuid::Uuid;
#[test]
fn connector_list() {
let connector_list = types::ConnectorsList {
connectors: vec![String::from("stripe"), "adyen".to_string()],
};
let json = serde_json::to_string(&connector_list).unwrap();
println!("{}", &json);
let newlist: types::ConnectorsList = serde_json::from_str(&json).unwrap();
println!("{newlist:#?}");
assert_eq!(true, true);
}
#[cfg(feature = "v1")]
// FIXME: broken test?
#[ignore]
#[actix_rt::test]
async fn payments_create_core() {
use router::configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
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
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 10:11:12)),
confirm: Some(true),
customer_id: None,
email: None,
name: None,
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: None,
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "4242424242424242".to_string().try_into().unwrap(),
card_exp_month: "10".to_string().into(),
card_exp_year: "35".to_string().into(),
card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Hyperswitch".to_string()),
statement_descriptor_suffix: Some("Hyperswitch".to_string()),
..<_>::default()
};
let expected_response = api::PaymentsResponse {
payment_id,
status: api_enums::IntentStatus::Succeeded,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
ephemeral_key: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
order_tax_amount: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
merchant_account,
None,
key_store,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
None,
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
// FIXME: broken test? It looks like we haven't updated the test after removing the `core::payments::payments_start_core` method from the codebase.
// #[ignore]
// #[actix_rt::test]
// async fn payments_start_core_stripe_redirect() {
// use router::configs::settings::Settings;
// let conf = Settings::new().expect("invalid settings");
//
// let state = routes::AppState {
// flow_name: String::from("default"),
// pg_pool: connection::make_pg_pool(&conf).await,
// redis_conn: connection::redis_connection(&conf).await,
// };
//
// let customer_id = format!("cust_{}", Uuid::new_v4());
// let merchant_id = "jarnura".to_string();
// let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();
// let customer_data = api::CreateCustomerRequest {
// customer_id: customer_id.clone(),
// merchant_id: merchant_id.clone(),
// ..api::CreateCustomerRequest::default()
// };
//
// let _customer = customer_data.insert(&*state.store).await.unwrap();
//
// let merchant_account = services::authenticate(&state, "123").await.unwrap();
// let payment_attempt = storage::PaymentAttempt::find_by_payment_id_merchant_id(
// &*state.store,
// &payment_id,
// &merchant_id,
// )
// .await
// .unwrap();
// let payment_intent = storage::PaymentIntent::find_by_payment_id_merchant_id(
// &*state.store,
// &payment_id,
// &merchant_id,
// )
// .await
// .unwrap();
// let payment_intent_update = storage::PaymentIntentUpdate::ReturnUrlUpdate {
// return_url: "http://example.com/payments".to_string(),
// status: None,
// };
// payment_intent
// .update(&*state.store, payment_intent_update)
// .await
// .unwrap();
//
// let expected_response = services::ApplicationResponse::Form(services::RedirectForm {
// url: "http://example.com/payments".to_string(),
// method: services::Method::Post,
// form_fields: HashMap::from([("payment_id".to_string(), payment_id.clone())]),
// });
// let actual_response = payments_start_core(
// &state,
// merchant_account,
// api::PaymentsStartRequest {
// payment_id,
// merchant_id,
// txn_id: payment_attempt.txn_id.to_owned(),
// },
// )
// .await
// .unwrap();
// assert_eq!(expected_response, actual_response);
// }
#[cfg(feature = "v1")]
// FIXME: broken test?
#[ignore]
#[actix_rt::test]
async fn payments_create_core_adyen_no_redirect() {
use router::configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let customer_id = format!("cust_{}", Uuid::new_v4());
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
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
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 10:11:12)),
confirm: Some(true),
customer_id: Some(id_type::CustomerId::try_from(Cow::from(customer_id)).unwrap()),
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OffSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(),
card_exp_month: "03".to_string().into(),
card_exp_year: "2030".to_string().into(),
card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "737".to_string().into(),
bank_code: None,
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Juspay".to_string()),
statement_descriptor_suffix: Some("Router".to_string()),
..Default::default()
};
let expected_response = services::ApplicationResponse::JsonWithHeaders((
api::PaymentsResponse {
payment_id: payment_id.clone(),
status: api_enums::IntentStatus::Processing,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
ephemeral_key: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
order_tax_amount: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
},
vec![],
));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
merchant_account,
None,
key_store,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
None,
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
| 4,036 | 1,103 |
hyperswitch | crates/router/tests/payouts.rs | .rs | #![allow(clippy::unwrap_used, clippy::print_stdout)]
mod utils;
#[actix_web::test]
async fn payouts_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let get_endpoints = vec!["retrieve", "accounts"];
let post_endpoints = vec!["create", "update", "reverse", "cancel"];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/payouts/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
for endpoint in post_endpoints {
response = client
.post(format!("http://127.0.0.1:8080/payouts/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
}
| 291 | 1,104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.