Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(revenue_recovery): index retry ladder by total invoice attempts (#13667)
CHALLA NISHANTH BABUfe09a801ffe5
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex cbae365895..dae939ea75 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -458,8 +458,10 @@ pub enum RevenueRecoveryError {PaymentIntentCreateFailed,#[error("Source verification failed for billing connector")]WebhookAuthenticationFailed,- #[error("Payment merchant connector account not found using account reference id")]- PaymentMerchantConnectorAccountNotFound,+ #[error("Payment merchant connector account {id} not found using account reference id")]+ PaymentMerchantConnectorAccountNotFound { id: String },+ #[error("Payment attempt cannot be recorded while the invoice is in {status} state")]+ PaymentAttemptRecordNotAllowed { status: String },#[error("Failed to fetch primitive date_time")]ScheduleTimeFetchFailed,#[error("Failed to create process tracker")]@@ -485,3 +487,49 @@ pub enum RevenueRecoveryError {#[error("Failed to insert the revenue recovery payment method data in redis")]RevenueRecoveryRedisInsertFailed,}++#[cfg(all(feature = "revenue_recovery", feature = "v2"))]+impl common_utils::errors::ErrorSwitch<ApiErrorResponse> for RevenueRecoveryError {+ fn switch(&self) -> ApiErrorResponse {+ match self {+ Self::WebhookAuthenticationFailed => ApiErrorResponse::WebhookAuthenticationFailed,+ Self::InvoiceWebhookProcessingFailed+ | Self::TransactionWebhookProcessingFailed+ | Self::RevenueRecoveryAttemptDataCreateFailed+ | Self::CustomerIdNotFound => ApiErrorResponse::WebhookUnprocessableEntity,++ Self::PaymentMerchantConnectorAccountNotFound { id } => {+ ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone() }+ }+ Self::PaymentAttemptRecordNotAllowed { status } => {+ ApiErrorResponse::PreconditionFailed {+ message: format!(+ "payment attempt cannot be recorded because the invoice is already in \+ {status} state"+ ),+ }+ }++ Self::BillingThresholdRetryCountFetchFailed => {+ ApiErrorResponse::InvalidConnectorConfiguration {+ config: "revenue_recovery.billing_connector_retry_threshold".to_string(),+ }+ }++ Self::PaymentAttemptIdNotFound | Self::RetryAlgorithmTypeNotFound => {+ ApiErrorResponse::WebhookResourceNotFound+ }+ Self::PaymentIntentFetchFailed+ | Self::PaymentAttemptFetchFailed+ | Self::PaymentIntentCreateFailed+ | Self::ScheduleTimeFetchFailed+ | Self::ProcessTrackerCreationError+ | Self::ProcessTrackerResponseError+ | Self::BillingConnectorPaymentsSyncFailed+ | Self::BillingConnectorInvoiceSyncFailed+ | Self::RetryCountFetchFailed+ | Self::RetryAlgorithmUpdationFailed+ | Self::RevenueRecoveryRedisInsertFailed => ApiErrorResponse::WebhookProcessingFailure,+ }+ }+}diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex 78e936e0ff..87f8d8c10d 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -138,13 +138,23 @@ pub async fn upsert_calculate_pcr_task(let task = "CALCULATE_WORKFLOW";let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;+ // The ladder is indexed by attempts already made on the invoice, so seeding it with+ // anything else replays the slots the billing connector already consumed.+ let attempts_already_made = i32::from(intent_retry_count);++ router_env::logger::info!(+ payment_id = %payment_id.get_string_repr(),+ attempts_already_made,+ "Seeding CALCULATE_WORKFLOW retry count from attempts already made"+ );+let process_tracker_entry = storage::ProcessTrackerNew::new(process_tracker_id,task,runner,tag,calculate_workflow_tracking_data,- Some(1),+ Some(attempts_already_made),schedule_time,common_types::consts::API_VERSION,state.conf.application_source,@@ -753,6 +763,32 @@ pub async fn perform_calculate_workflow().await?;}+ revenue_recovery_workflow::PaymentProcessorTokenResponse::RetriesExhausted => {+ // Rescheduling here would keep the job alive forever without ever retrying a payment.+ logger::info!(+ process_id = %process.id,+ connector_customer_id = %connector_customer_id,+ retry_count = process.retry_count,+ "Retry ladder exhausted, finishing CALCULATE_WORKFLOW"+ );++ db.as_scheduler()+ .finish_process_with_business_status(+ process.clone(),+ business_status::RETRIES_EXCEEDED,+ )+ .await+ .map_err(|e| {+ logger::error!(+ process_id = %process.id,+ error = ?e,+ "Failed to finish CALCULATE_WORKFLOW after exhausting retries"+ );+ sch_errors::ProcessTrackerError::ProcessUpdateFailed+ })?;++ event_type = Some(common_enums::EventType::PaymentFailed);+ }revenue_recovery_workflow::PaymentProcessorTokenResponse::HardDecline => {// Finish calculate workflow with CALCULATE_WORKFLOW_FINISHlogger::info!(diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex 1df5e66420..b12daa582f 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -1476,7 +1476,14 @@ pub async fn reopen_calculate_workflow_on_payment_failure(.reopen_workflow_buffer_time_in_seconds,);- let new_retry_count = process.retry_count + 1;+ // `process` is the EXECUTE tracker, which only counts our own attempts. The calculate+ // ladder needs the invoice total, so take it from the intent metadata instead.+ let new_retry_count = payment_intent+ .feature_metadata+ .as_ref()+ .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())+ .map(|recovery_metadata| i32::from(recovery_metadata.total_retry_count))+ .unwrap_or(process.retry_count + 1);// Check if a process tracker entry already exists for this payment intentlet existing_entry = dbdiff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rsindex 7d9cbbdc9a..c7ce7d6478 100644--- a/crates/router/src/core/webhooks/incoming_v2.rs+++ b/crates/router/src/core/webhooks/incoming_v2.rs@@ -363,7 +363,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(&object_ref_id,)).await- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .switch().attach_printable("Failed to process recovery incoming webhook")?}}diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rsindex 19ed1c3813..8f48e90f64 100644--- a/crates/router/src/core/webhooks/recovery_incoming.rs+++ b/crates/router/src/core/webhooks/recovery_incoming.rs@@ -124,6 +124,34 @@ pub async fn recovery_incoming_webhook_flow(billing_connector_invoice_details.as_ref(),)?;+ let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();++ // Resolve the gateway before persistence to avoid creating records for an unmapped account.+ let resolved_transaction_details = if is_event_recovery_transaction_event {+ let invoice_transaction_details =+ RevenueRecoveryAttempt::get_recovery_invoice_transaction_details(+ connector_enum,+ request_details,+ billing_connector_payment_details.as_ref(),+ &invoice_details.0,+ )?;++ let payment_merchant_connector_account = invoice_transaction_details+ .find_payment_merchant_connector_account(+ &state,+ platform.get_processor().get_key_store(),+ &billing_connector_account,+ )+ .await?;++ Some((+ invoice_transaction_details,+ payment_merchant_connector_account,+ ))+ } else {+ None+ };+// Fetch the intent using merchant reference id, if not found create new intent.let payment_intent = invoice_details.get_payment_intent(&state, &req_state, &platform, &business_profile)@@ -136,20 +164,15 @@ pub async fn recovery_incoming_webhook_flow(}).await?;- let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =RevenueRecoveryAttempt::get_recovery_payment_attempt(- is_event_recovery_transaction_event,+ resolved_transaction_details,&billing_connector_account,&state,- connector_enum,&req_state,- billing_connector_payment_details.as_ref(),- request_details,&platform,&business_profile,&payment_intent,- &invoice_details.0,).await?;@@ -791,9 +814,18 @@ impl RevenueRecoveryAttempt {}Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed).attach_printable("Unexpected response from record attempt core"),- error @ Err(_) => {+ Err(error) => {logger::error!(?error);- Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)+ // Retrying cannot record another attempt after the invoice reaches a final state.+ let recovery_error = match error.current_context() {+ errors::ApiErrorResponse::PaymentUnexpectedState { current_value, .. } => {+ errors::RevenueRecoveryError::PaymentAttemptRecordNotAllowed {+ status: current_value.clone(),+ }+ }+ _ => errors::RevenueRecoveryError::PaymentAttemptFetchFailed,+ };+ Err(recovery_error).attach_printable("failed to record attempt in recovery webhook flow")}}?;@@ -897,42 +929,54 @@ impl RevenueRecoveryAttempt {state: &SessionState,key_store: &domain::MerchantKeyStore,billing_connector_account: &domain::MerchantConnectorAccount,- ) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> {+ ) -> CustomResult<domain::MerchantConnectorAccount, errors::RevenueRecoveryError> {+ let connector_account_reference_id = &self.0.connector_account_reference_id;+let payment_merchant_connector_account_id = billing_connector_account.get_payment_merchant_connector_account_id_using_account_reference_id(- self.0.connector_account_reference_id.clone(),- );+ connector_account_reference_id.clone(),+ )+ .ok_or(report!(+ errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound {+ id: connector_account_reference_id.clone()+ }+ ))+ .attach_printable_lazy(|| {+ format!(+ "no payment merchant connector account is mapped to account reference id \+ {connector_account_reference_id} in the feature metadata of billing connector \+ account {}",+ billing_connector_account.get_id().get_string_repr()+ )+ })?;+let db = &*state.store;- let payment_merchant_connector_account = payment_merchant_connector_account_id- .as_ref()- .async_map(|mca_id| async move {- db.find_merchant_connector_account_by_id(mca_id, key_store)- .await- })+ db.find_merchant_connector_account_by_id(&payment_merchant_connector_account_id, key_store).await- .transpose()- .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)- .attach_printable(- "failed to fetch payment merchant connector id using account reference id",- )?;- Ok(payment_merchant_connector_account)+ .change_context(+ errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound {+ id: payment_merchant_connector_account_id+ .get_string_repr()+ .to_string(),+ },+ )+ .attach_printable_lazy(|| {+ format!(+ "failed to fetch payment merchant connector account {} mapped to account \+ reference id {connector_account_reference_id}",+ payment_merchant_connector_account_id.get_string_repr()+ )+ })}- #[allow(clippy::too_many_arguments)]async fn get_recovery_payment_attempt(- is_recovery_transaction_event: bool,+ resolved_transaction_details: Option<(Self, domain::MerchantConnectorAccount)>,billing_connector_account: &domain::MerchantConnectorAccount,state: &SessionState,- connector_enum: &connector_integration_interface::ConnectorEnum,req_state: &ReqState,- billing_connector_payment_details: Option<- &revenue_recovery_response::BillingConnectorPaymentsSyncResponse,- >,- request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,platform: &domain::Platform,business_profile: &domain::Profile,payment_intent: &revenue_recovery::RecoveryPaymentIntent,- invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,) -> CustomResult<(Option<revenue_recovery::RecoveryPaymentAttempt>,@@ -940,29 +984,12 @@ impl RevenueRecoveryAttempt {),errors::RevenueRecoveryError,> {- let payment_attempt_with_recovery_intent = match is_recovery_transaction_event {- true => {- let mut invoice_transaction_details =- Self::get_recovery_invoice_transaction_details(- connector_enum,- request_details,- billing_connector_payment_details,- invoice_details,- )?;-+ let payment_attempt_with_recovery_intent = match resolved_transaction_details {+ Some((mut invoice_transaction_details, payment_merchant_connector_account)) => {// Boxed to keep this future off the enclosing state machine, the recovery webhook// chain is deep enough that inlining it can overflow the worker thread's stack.Box::pin(invoice_transaction_details.enrich_card_info_using_card_bin(state)).await;- // Find the payment merchant connector ID at the top level to avoid multiple DB calls.- let payment_merchant_connector_account = invoice_transaction_details- .find_payment_merchant_connector_account(- state,- platform.get_processor().get_key_store(),- billing_connector_account,- )- .await?;-let (payment_attempt, updated_payment_intent) = invoice_transaction_details.get_payment_attempt(state,@@ -982,7 +1009,7 @@ impl RevenueRecoveryAttempt {business_profile,payment_intent,&billing_connector_account.get_id(),- payment_merchant_connector_account,+ Some(payment_merchant_connector_account),).await})@@ -990,7 +1017,7 @@ impl RevenueRecoveryAttempt {(Some(payment_attempt), updated_payment_intent)}- false => (None, payment_intent.clone()),+ None => (None, payment_intent.clone()),};Ok(payment_attempt_with_recovery_intent)@@ -1312,7 +1339,7 @@ impl BillingConnectorInvoiceSyncResponseData {Ok(response) => Ok(response),error @ Err(_) => {logger::error!(?error);- Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)+ Err(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed).attach_printable("Failed while fetching billing connector Invoice details")}}?;diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex 280371c8a3..c18e5d7be1 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -630,6 +630,9 @@ pub enum PaymentProcessorTokenResponse {next_available_time: time::PrimitiveDateTime,},+ /// The configured retry ladder has no slot left for this invoice+ RetriesExhausted,+/// No retry info available / nothing to do yetNone,}@@ -664,14 +667,20 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(let dimensions = crate::core::configs::dimension_state::Dimensions::new().with_processor_merchant_id(payment_intent.merchant_id.clone().into()).with_connector(billing_connector);- let time = get_schedule_time_to_retry_mit_payments(+ let schedule_time = get_schedule_time_to_retry_mit_payments(state.store.as_ref(),state.superposition_service.as_ref(),&dimensions,retry_count,)- .await- .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;+ .await;++ // Distinct from `None` below, which means "no token right now, come back later" and+ // keeps the calculate job alive.+ let Some(time) = schedule_time else {+ logger::info!(retry_count, "Retry ladder exhausted for this invoice");+ return Ok((PaymentProcessorTokenResponse::RetriesExhausted, None));+ };payment_processor_token_response = get_token_availability_for_schedule_time(state,@@ -783,6 +792,10 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(logger::info!("Next available retry at {:?}", next_available_time);}+ PaymentProcessorTokenResponse::RetriesExhausted => {+ logger::debug!("Retry ladder exhausted");+ }+PaymentProcessorTokenResponse::None => {logger::debug!("No retry info available");}diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rsindex ef867a6eff..46b35c31a9 100644--- a/crates/scheduler/src/utils.rs+++ b/crates/scheduler/src/utils.rs@@ -495,4 +495,59 @@ mod tests {);}}++ /// `start_after` is the delay before attempt #1 (the initial charge) and each `frequencies`+ /// slot is the delay before one retry, so `N` slots describe the charge plus `N` retries.+ fn walk_pcr_ladder(+ mapping: &process_data::RetryMapping,+ attempts_already_made: i32,+ ) -> (usize, i32) {+ let mut retry_count = attempts_already_made;+ let mut elapsed = 0;+ let mut attempts = 0;++ while let Some(delay) = get_pcr_payments_retry_schedule_time(+ process_data::RevenueRecoveryPaymentProcessTrackerMapping {+ default_mapping: mapping.clone(),+ },+ retry_count,+ ) {+ elapsed += delay;+ attempts += 1;+ retry_count += 1;+ }++ (attempts, elapsed)+ }++ /// 15 retries are budgeted on top of the initial charge. The billing connector takes the first+ /// and holds the last back for day 30, so the ladder covers the 14 in between and then stops.+ #[test]+ fn test_pcr_retry_ladder_leaves_thirteen_retries_to_us_ending_on_day_twenty_eight() {+ const DAY: i32 = 24 * 60 * 60;+ const BILLING_CONNECTOR_RETRY_THRESHOLD: i32 = 2;++ let mapping = process_data::RetryMapping {+ start_after: DAY,+ frequencies: vec![+ (2 * DAY, 1),+ (5 * DAY, 1),+ (2 * DAY, 1),+ (2 * DAY, 1),+ (138_240, 10),+ ],+ };++ // The last laddered retry lands on day 28, two days clear of the day 30 one.+ let (attempts, elapsed) = walk_pcr_ladder(&mapping, 0);+ assert_eq!(+ attempts, 15,+ "ladder must cover the initial charge plus 14 retries"+ );+ assert_eq!(elapsed, 28 * DAY, "last laddered retry must land on day 28");++ // We take over once the charge and the billing connector's first retry have both failed.+ let (attempts, _) = walk_pcr_ladder(&mapping, BILLING_CONNECTOR_RETRY_THRESHOLD);+ assert_eq!(attempts, 13, "we must schedule exactly 13 retries");+ }}