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
feat(revenue_recovery): add card_switching_enabled flag to choose the retry card (#15090)
CHALLA NISHANTH BABU6b96382a6ce0
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 1641907faa..b51678a392 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -483,6 +483,9 @@ pub mod superposition {/// Whether the adaptive revenue recovery retry algorithm — static ladder combined with/// the smart algorithm — replaces the decider-based smart retry implementationpub const ADAPTIVE_RETRY_ENABLED: &str = "revenue_recovery.adaptive_retry_enabled";+ /// Whether a retry may be made with any of the customer's cards stored in redis, rather than+ /// only the card the invoice last used — whichever algorithm decides when it runs+ pub const CARD_SWITCHING_ENABLED: &str = "revenue_recovery.card_switching_enabled";/// Whether A/B routing decides which retry implementation an invoice runs.pub const REVENUE_RECOVERY_AB_ENABLED: &str = "revenue_recovery.ab_enabled";/// Which retry implementation inside the `Smart` arm an invoice runs under A/B routing.diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 7233647af2..daf3166e92 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -804,6 +804,24 @@ impl DatabaseBackedConfig for AdaptiveRetryEnabled {}}+config! {+ superposition_key = CARD_SWITCHING_ENABLED,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for CardSwitchingEnabled {+ const KEY: &'static str = "card_switching_enabled";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_processor_merchant_id()+ .map(|merchant_id| format!("{}_{}", merchant_id.get_string_repr(), Self::KEY))+ }+}+config! {superposition_key = REVENUE_RECOVERY_AB_ENABLED,output = bool,diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex d9c01af043..611aa46124 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -1,4 +1,5 @@pub mod api;+pub mod card_selection;pub mod retry_stats;pub mod schedule;pub mod transformers;@@ -30,6 +31,7 @@ use hyperswitch_domain_models::{},platform, revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor,};+use hyperswitch_masking::{PeekInterface, Secret};use scheduler::errors as sch_errors;use crate::{@@ -211,6 +213,7 @@ pub async fn upsert_calculate_pcr_task(intent_retry_count,max_hybrid_cascading_retry_count,)),+ payment_processor_token: None,};let tag = ["PCR"];@@ -421,45 +424,67 @@ pub async fn perform_execute_payment(types::Decision::Execute => {let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id();- let last_token_used =- revenue_recovery_workflow::get_invoice_payment_processor_token(payment_intent);+ let processor_token = match tracking_data.payment_processor_token.as_ref() {+ // Calculate records the card it picked on the task, so the payment is made with+ // exactly that card+ Some(payment_processor_token) => {+ storage::revenue_recovery_redis_operation::RedisTokenManager::get_retryable_token_using_token_id(+ state,+ &connector_customer_id,+ payment_processor_token.peek(),+ )+ .await+ }- // Same dimensions calculate resolves the flag on- let adaptive_retry_enabled = crate::core::configs::dimension_state::Dimensions::new()- .with_processor_merchant_id(payment_intent.merchant_id.clone().into())- .with_connector(revenue_recovery_payment_data.billing_mca.connector_name)- .get_adaptive_retry_enabled(- state.store.as_ref(),- state.superposition_service.as_ref(),- None,- )- .await;+ // Queued before calculate recorded its pick, so the card is resolved the way it was+ // when the task was queued+ None => {+ let last_token_used =+ revenue_recovery_workflow::get_invoice_payment_processor_token(+ payment_intent,+ );++ // Same dimensions calculate resolves the flag on+ let adaptive_retry_enabled =+ crate::core::configs::dimension_state::Dimensions::new()+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())+ .with_connector(revenue_recovery_payment_data.billing_mca.connector_name)+ .get_adaptive_retry_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await;- // Same dimensions calculate resolves the flag on- let ab_enabled = crate::core::configs::dimension_state::Dimensions::new()- .with_processor_merchant_id(payment_intent.merchant_id.clone().into())- .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())- .with_organization_id(payment_intent.organization_id.clone())- .with_profile_id(payment_intent.profile_id.clone())- .get_revenue_recovery_ab_enabled(- state.store.as_ref(),- state.superposition_service.as_ref(),- None,- )- .await;+ // Same dimensions calculate resolves the flag on+ let ab_enabled = crate::core::configs::dimension_state::Dimensions::new()+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())+ .with_provider_merchant_id(+ platform.get_provider().get_provider_merchant_id(),+ )+ .with_organization_id(payment_intent.organization_id.clone())+ .with_profile_id(payment_intent.profile_id.clone())+ .get_revenue_recovery_ab_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await;- // Calculate schedules the invoice's own token on both the A/B and adaptive paths, and- // hands the invoice to the decider only when neither is on.- let smart_retry_uses_invoice_token = ab_enabled || adaptive_retry_enabled;+ // Calculate schedules the invoice's own token on both the A/B and adaptive+ // paths, and hands the invoice to the decider only when neither is on.+ let smart_retry_uses_invoice_token = ab_enabled || adaptive_retry_enabled;- let processor_token = storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(- state,- &connector_customer_id,- tracking_data.revenue_recovery_retry,- last_token_used.as_deref(),- smart_retry_uses_invoice_token,- )- .await+ storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(+ state,+ &connector_customer_id,+ tracking_data.revenue_recovery_retry,+ last_token_used.as_deref(),+ smart_retry_uses_invoice_token,+ )+ .await+ }+ }.change_context(errors::ApiErrorResponse::GenericNotFoundError {message: "Failed to fetch token details from redis".to_string(),})?;@@ -646,6 +671,7 @@ async fn insert_psync_pcr_task_to_pt(revenue_recovery_retry,invoice_scheduled_time: Some(schedule_time),static_ladder_progress,+ payment_processor_token: None,};let tag = ["REVENUE_RECOVERY"];let process_tracker_entry = storage::ProcessTrackerNew::new(@@ -990,6 +1016,7 @@ pub async fn perform_calculate_workflow(match payment_processor_token_response {revenue_recovery_workflow::PaymentProcessorTokenResponse::ScheduledTime {scheduled_time,+ payment_processor_token,} => {logger::info!(process_id = %process.id,@@ -1018,6 +1045,7 @@ pub async fn perform_calculate_workflow(retry_algorithm_type,scheduled_time,next_static_ladder_progress.clone(),+ payment_processor_token,).await?;@@ -1327,6 +1355,7 @@ async fn insert_execute_pcr_task_to_pt(revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,schedule_time: time::PrimitiveDateTime,static_ladder_progress: Option<schedule::StaticLadderProgress>,+ payment_processor_token: String,) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> {let task = "EXECUTE_WORKFLOW";@@ -1373,6 +1402,7 @@ async fn insert_execute_pcr_task_to_pt(tracking_data.revenue_recovery_retry = revenue_recovery_retry;tracking_data.static_ladder_progress = static_ladder_progress;tracking_data.prev_attempt_error_code = prev_attempt_error_code;+ tracking_data.payment_processor_token = Some(Secret::new(payment_processor_token));let tracking_data_json = serde_json::to_value(&tracking_data).change_context(errors::RecoveryError::ValueNotFound)@@ -1439,6 +1469,7 @@ async fn insert_execute_pcr_task_to_pt(revenue_recovery_retry,invoice_scheduled_time: Some(schedule_time),static_ladder_progress,+ payment_processor_token: Some(Secret::new(payment_processor_token)),};let tag = ["PCR"];diff --git a/crates/router/src/core/revenue_recovery/card_selection.rs b/crates/router/src/core/revenue_recovery/card_selection.rsnew file mode 100644index 0000000000..f836b1671d--- /dev/null+++ b/crates/router/src/core/revenue_recovery/card_selection.rs@@ -0,0 +1,320 @@+use std::collections::HashMap;++use crate::types::storage::revenue_recovery_redis_operation::{+ PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo,+};++/// Which of the customer's cards a retry may be made with. Set by the card switching flag alone,+/// so it is the same whichever algorithm decides when the retry runs.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CardSelection {+ /// Only the card the invoice last used.+ InvoiceCard,+ /// Any of the customer's active cards stored in redis.+ AnyCard,+}++impl CardSelection {+ pub fn from_card_switching_enabled(card_switching_enabled: bool) -> Self {+ if card_switching_enabled {+ Self::AnyCard+ } else {+ Self::InvoiceCard+ }+ }++ /// Whether the retry may be made with this card.+ pub fn admits(+ self,+ payment_processor_token: &str,+ token_status: &PaymentProcessorTokenStatus,+ invoice_token: Option<&str>,+ ) -> bool {+ match self {+ // By id alone, as the invoice's card has always been resolved+ Self::InvoiceCard => invoice_token == Some(payment_processor_token),+ Self::AnyCard => token_status.is_active != Some(false),+ }+ }+}++/// Where the cards a retry may be made with stand, once the algorithm has decided its time.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum CardAvailability {+ /// This card can be retried at the decided time.+ Ready { payment_processor_token: String },+ /// No card can be retried yet; the soonest frees up after this many hours.+ WaitHours(i64),+ /// Every card the retry may be made with is hard declined.+ HardDecline,+ /// The retry has no card to be made with.+ NoCard,+}++/// Pick the card for a retry whose time the algorithm has already decided. A card that is hard+/// declined is never picked, and one still waiting out its network's retry limits is not ready.+/// Of the ready cards, one with no failure on record is preferred, then the invoice's own card,+/// then the one with the most retries left this month.+pub fn pick_card_for_retry_time(+ card_selection: CardSelection,+ tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,+ invoice_token: Option<&str>,+) -> CardAvailability {+ let admitted_cards: Vec<_> = tokens+ .iter()+ .filter(|(payment_processor_token, token)| {+ card_selection.admits(payment_processor_token, &token.token_status, invoice_token)+ })+ .collect();++ if admitted_cards.is_empty() {+ return CardAvailability::NoCard;+ }++ let retryable_cards: Vec<_> = admitted_cards+ .into_iter()+ .filter(|(_, token)| !token.token_status.is_hard_decline.unwrap_or(false))+ .collect();++ let ready_card = retryable_cards+ .iter()+ .filter(|(_, token)| token.retry_wait_time_hours <= 0)+ .min_by_key(|&&(payment_processor_token, token)| {+ (+ token.token_status.error_code.is_some(),+ invoice_token != Some(payment_processor_token.as_str()),+ std::cmp::Reverse(token.monthly_retry_remaining),+ // Last, so the pick does not depend on the map's order+ payment_processor_token.as_str(),+ )+ });++ match ready_card {+ Some((payment_processor_token, _)) => CardAvailability::Ready {+ payment_processor_token: (*payment_processor_token).clone(),+ },+ None => retryable_cards+ .iter()+ .map(|(_, token)| token.retry_wait_time_hours)+ .min()+ .map_or(CardAvailability::HardDecline, CardAvailability::WaitHours),+ }+}++#[cfg(test)]+mod tests {+ use common_utils::id_type;++ use super::*;+ use crate::types::storage::revenue_recovery_redis_operation::PaymentProcessorTokenDetails;++ const INVOICE_CARD: &str = "invoice_card";++ #[derive(Clone, Copy)]+ struct Card {+ failed: bool,+ hard_declined: bool,+ active: bool,+ wait_hours: i64,+ retries_left: i32,+ }++ /// A card that last failed softly and can be retried right away.+ const SOFT_DECLINED: Card = Card {+ failed: true,+ hard_declined: false,+ active: true,+ wait_hours: 0,+ retries_left: 10,+ };++ fn tokens(cards: &[(&str, Card)]) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {+ let cell_id = id_type::CellId::from_string("00").expect("valid cell id");+ cards+ .iter()+ .map(|&(payment_processor_token, card)| {+ let token_status = PaymentProcessorTokenStatus {+ payment_processor_token_details: PaymentProcessorTokenDetails {+ payment_processor_token: payment_processor_token.to_string(),+ expiry_month: None,+ expiry_year: None,+ card_issuer: None,+ last_four_digits: None,+ card_network: None,+ card_type: None,+ card_isin: None,+ },+ inserted_by_attempt_id: id_type::GlobalAttemptId::generate(&cell_id),+ error_code: card.failed.then(|| "card_declined".to_string()),+ daily_retry_history: HashMap::new(),+ scheduled_at: None,+ is_hard_decline: Some(card.hard_declined),+ modified_at: None,+ is_active: Some(card.active),+ account_update_history: None,+ decision_threshold: None,+ };+ (+ payment_processor_token.to_string(),+ PaymentProcessorTokenWithRetryInfo {+ token_status,+ retry_wait_time_hours: card.wait_hours,+ monthly_retry_remaining: card.retries_left,+ total_30_day_retries: 0,+ },+ )+ })+ .collect()+ }++ fn ready(payment_processor_token: &str) -> CardAvailability {+ CardAvailability::Ready {+ payment_processor_token: payment_processor_token.to_string(),+ }+ }++ fn pick(card_selection: CardSelection, cards: &[(&str, Card)]) -> CardAvailability {+ pick_card_for_retry_time(card_selection, &tokens(cards), Some(INVOICE_CARD))+ }++ #[test]+ fn invoice_card_selection_never_switches_cards() {+ let clean = Card {+ failed: false,+ ..SOFT_DECLINED+ };+ let hard_declined = Card {+ hard_declined: true,+ ..SOFT_DECLINED+ };+ let waiting = Card {+ wait_hours: 5,+ ..SOFT_DECLINED+ };++ for (cards, expected) in [+ (+ vec![(INVOICE_CARD, SOFT_DECLINED), ("other", clean)],+ ready(INVOICE_CARD),+ ),+ (+ vec![(INVOICE_CARD, hard_declined), ("other", clean)],+ CardAvailability::HardDecline,+ ),+ (+ vec![(INVOICE_CARD, waiting), ("other", clean)],+ CardAvailability::WaitHours(5),+ ),+ (vec![("other", clean)], CardAvailability::NoCard),+ ] {+ assert_eq!(pick(CardSelection::InvoiceCard, &cards), expected);+ }+ }++ #[test]+ fn invoice_card_selection_keeps_a_deactivated_invoice_card() {+ let deactivated = Card {+ active: false,+ ..SOFT_DECLINED+ };+ assert_eq!(+ pick(CardSelection::InvoiceCard, &[(INVOICE_CARD, deactivated)]),+ ready(INVOICE_CARD)+ );+ }++ #[test]+ fn any_card_selection_prefers_a_card_with_no_failure_then_the_invoice_card() {+ let clean = Card {+ failed: false,+ ..SOFT_DECLINED+ };+ let more_retries_left = Card {+ retries_left: 20,+ ..SOFT_DECLINED+ };++ assert_eq!(+ pick(+ CardSelection::AnyCard,+ &[(INVOICE_CARD, SOFT_DECLINED), ("clean", clean)]+ ),+ ready("clean")+ );+ assert_eq!(+ pick(+ CardSelection::AnyCard,+ &[(INVOICE_CARD, SOFT_DECLINED), ("other", more_retries_left)]+ ),+ ready(INVOICE_CARD)+ );+ assert_eq!(+ pick(+ CardSelection::AnyCard,+ &[("other", SOFT_DECLINED), ("more", more_retries_left)]+ ),+ ready("more")+ );+ }++ #[test]+ fn any_card_selection_switches_away_from_an_unusable_invoice_card() {+ for unusable in [+ Card {+ hard_declined: true,+ ..SOFT_DECLINED+ },+ Card {+ active: false,+ ..SOFT_DECLINED+ },+ Card {+ wait_hours: 5,+ ..SOFT_DECLINED+ },+ ] {+ assert_eq!(+ pick(+ CardSelection::AnyCard,+ &[(INVOICE_CARD, unusable), ("other", SOFT_DECLINED)]+ ),+ ready("other")+ );+ }+ }++ #[test]+ fn any_card_selection_waits_for_the_soonest_card_and_stops_on_hard_declines() {+ let waiting = |wait_hours| Card {+ wait_hours,+ ..SOFT_DECLINED+ };+ let hard_declined = Card {+ hard_declined: true,+ ..SOFT_DECLINED+ };+ let deactivated = Card {+ active: false,+ ..SOFT_DECLINED+ };++ assert_eq!(+ pick(+ CardSelection::AnyCard,+ &[(INVOICE_CARD, waiting(9)), ("other", waiting(3))]+ ),+ CardAvailability::WaitHours(3)+ );+ assert_eq!(+ pick(+ CardSelection::AnyCard,+ &[(INVOICE_CARD, hard_declined), ("other", hard_declined)]+ ),+ CardAvailability::HardDecline+ );+ assert_eq!(+ pick(CardSelection::AnyCard, &[(INVOICE_CARD, deactivated)]),+ CardAvailability::NoCard+ );+ }+}diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex b8c7b6ffaa..323fa11564 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -1391,6 +1391,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure(billing_mca_id: old_tracking_data.billing_mca_id.clone(),invoice_scheduled_time: old_tracking_data.invoice_scheduled_time,static_ladder_progress: old_tracking_data.static_ladder_progress,+ payment_processor_token: None,};let tracking_data = serde_json::to_value(new_tracking_data)diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rsindex eac2fff3fb..eb3a17239a 100644--- a/crates/router/src/types/storage/revenue_recovery.rs+++ b/crates/router/src/types/storage/revenue_recovery.rs@@ -9,7 +9,7 @@ use hyperswitch_domain_models::{payment_method_data::{Card, PaymentMethodData},payments::{payment_attempt::PaymentAttempt, PaymentIntent, PaymentStatusData},};-use hyperswitch_masking::PeekInterface;+use hyperswitch_masking::{PeekInterface, Secret};use router_env::logger;use serde::{Deserialize, Serialize};@@ -36,6 +36,10 @@ pub struct RevenueRecoveryWorkflowTrackingData {/// survives for the whole recovery lifecycle of an invoice.#[serde(default)]pub static_ladder_progress: Option<StaticLadderProgress>,+ /// The card calculate picked for the retry, which execute pays with. Only set on the EXECUTE+ /// row, and missing on rows queued before calculate recorded its pick.+ #[serde(default)]+ pub payment_processor_token: Option<Secret<String>>,}#[derive(Debug, Clone)]diff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rsindex 6a1c5625b1..4197661efa 100644--- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs+++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs@@ -970,7 +970,24 @@ impl RedisTokenManager {}}- // Get token based on retry type+ // Get the token calculate picked for a retry, unless it has been hard declined since+ pub async fn get_retryable_token_using_token_id(+ state: &SessionState,+ connector_customer_id: &str,+ payment_processor_token: &str,+ ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {+ let token = Self::get_payment_processor_token_using_token_id(+ state,+ connector_customer_id,+ payment_processor_token,+ )+ .await?;++ Self::discard_hard_declined_token(state, connector_customer_id, token).await+ }++ // Get token based on retry type, for an EXECUTE task queued before calculate recorded the+ // token it picked// The A/B and adaptive smart paths decide against the invoice's own token, so they resolve it// by id rather than the `scheduled_at` marker, which only the decider writes and is shared// across invoices.@@ -1006,6 +1023,15 @@ impl RedisTokenManager {}}+ Self::discard_hard_declined_token(state, connector_customer_id, token).await+ }++ // A hard declined token cannot be retried, so its schedule time is cleared and it is dropped+ async fn discard_hard_declined_token(+ state: &SessionState,+ connector_customer_id: &str,+ token: Option<PaymentProcessorTokenStatus>,+ ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {let token = match token {Some(t) => {if t.is_hard_decline.unwrap_or(false) {diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex 513d938e48..26e03db31e 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -72,7 +72,10 @@ use crate::{consts,core::{payments,- revenue_recovery::{self as pcr},+ revenue_recovery::{+ self as pcr,+ card_selection::{self, CardAvailability, CardSelection},+ },},db::StorageInterface,errors::StorageError,@@ -641,6 +644,8 @@ pub enum PaymentProcessorTokenResponse {/// Token can be retried at this specific timeScheduledTime {scheduled_time: time::PrimitiveDateTime,+ /// The card picked for the retry, which the EXECUTE task pays with+ payment_processor_token: String,},/// Token locked or unavailable, next attempt possible@@ -778,6 +783,20 @@ async fn get_ab_routed_retry_time((schedule_time, assigned_algorithm)}+/// When a retry runs, as the algorithm decides it. Which card it is made with is decided apart+/// from this, by the card selection.+#[cfg(feature = "v2")]+enum RetryTiming {+ /// One time for the invoice, from the cascading ladder or the retry model, with the ladder+ /// position to carry back if a retry is scheduled at it.+ At {+ retry_time: time::PrimitiveDateTime,+ next_static_ladder_progress: Option<pcr::schedule::StaticLadderProgress>,+ },+ /// The decider's time, asked of each card the selection admits.+ Decider,+}+#[cfg(feature = "v2")]#[allow(clippy::too_many_arguments)]pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(@@ -802,19 +821,29 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(),errors::ProcessTrackerError,> {- let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;- // Ladder position to write back onto the CALCULATE row. `None` leaves the stored count alone,- // which is the case for every outcome but one — see where it is set.- let mut next_static_ladder_progress = None;- match 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);++ // The algorithm below decides only when the retry runs. Which card it is made with is settled+ // here by the card switching flag alone, so it is the same whichever algorithm runs.+ let card_selection = CardSelection::from_card_switching_enabled(+ dimensions+ .get_card_switching_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await,+ );++ let retry_timing = match retry_algorithm_type {RevenueRecoveryAlgorithmType::Monitoring => {logger::error!("Monitoring type found for Revenue Recovery retry payment");+ return Ok((PaymentProcessorTokenResponse::None, None));}RevenueRecoveryAlgorithmType::Cascading => {- let dimensions = crate::core::configs::dimension_state::Dimensions::new()- .with_processor_merchant_id(payment_intent.merchant_id.clone().into())- .with_connector(billing_connector);let schedule_time = get_schedule_time_to_retry_mit_payments(state.store.as_ref(),state.superposition_service.as_ref(),@@ -830,20 +859,13 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(return Ok((PaymentProcessorTokenResponse::RetriesExhausted, None));};- payment_processor_token_response = get_token_availability_for_schedule_time(- state,- connector_customer_id,- payment_intent,- time,- )- .await?;+ RetryTiming::At {+ retry_time: time,+ next_static_ladder_progress: None,+ }}RevenueRecoveryAlgorithmType::Smart => {- let dimensions = crate::core::configs::dimension_state::Dimensions::new()- .with_processor_merchant_id(payment_intent.merchant_id.clone().into())- .with_connector(billing_connector);-let adaptive_retry_enabled = dimensions.get_adaptive_retry_enabled(state.store.as_ref(),@@ -1027,40 +1049,66 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type("Retry decision");- payment_processor_token_response = get_token_availability_for_schedule_time(- state,- connector_customer_id,- payment_intent,- decision.schedule_time,- )- .await?;+ RetryTiming::At {+ retry_time: decision.schedule_time,+ next_static_ladder_progress: Some(decision.next_progress),+ }+ } else {+ RetryTiming::Decider+ }+ }+ };++ // Ladder position to write back onto the CALCULATE row. `None` leaves the stored count alone,+ // which is the case for every outcome but one — see where it is set.+ let (mut payment_processor_token_response, next_static_ladder_progress) = match retry_timing {+ RetryTiming::At {+ retry_time,+ next_static_ladder_progress,+ } => {+ let payment_processor_token_response = get_token_availability_for_schedule_time(+ state,+ connector_customer_id,+ payment_intent,+ card_selection,+ retry_time,+ )+ .await?;- // The ladder position is carried back only when a retry is genuinely scheduled.- // The other responses finish or reschedule the CALCULATE job without an attempt.- if matches!(+ // The ladder position is carried back only when a retry is genuinely scheduled.+ // The other responses finish or reschedule the CALCULATE job without an attempt.+ let next_static_ladder_progress = next_static_ladder_progress.filter(|_| {+ matches!(payment_processor_token_response,PaymentProcessorTokenResponse::ScheduledTime { .. }- ) {- next_static_ladder_progress = Some(decision.next_progress);- }- } else {- payment_processor_token_response = get_best_psp_token_available_for_smart_retry(- state,- connector_customer_id,- payment_intent,)- .await- .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;- }+ });++ (+ payment_processor_token_response,+ next_static_ladder_progress,+ )}- }++ RetryTiming::Decider => (+ get_best_psp_token_available_for_smart_retry(+ state,+ connector_customer_id,+ payment_intent,+ card_selection,+ )+ .await+ .change_context(errors::ProcessTrackerError::EApiErrorResponse)?,+ None,+ ),+ };match &mut payment_processor_token_response {PaymentProcessorTokenResponse::HardDecline => {logger::debug!("Token is hard declined");}- PaymentProcessorTokenResponse::ScheduledTime { scheduled_time } => {+ PaymentProcessorTokenResponse::ScheduledTime { scheduled_time, .. } => {// Add random delay to schedule time*scheduled_time = add_random_delay_to_schedule_time(state, *scheduled_time);@@ -1117,16 +1165,17 @@ pub(crate) fn get_invoice_payment_processor_token(})}-/// Check the invoice's payment processor token against a schedule time already decided.+/// Pick the card for a schedule time already decided, from the cards the selection admits./// Shared by the cascading and model paths so both gate on the same conditions#[cfg(feature = "v2")]async fn get_token_availability_for_schedule_time(state: &SessionState,connector_customer_id: &str,payment_intent: &PaymentIntent,+ card_selection: CardSelection,scheduled_time: time::PrimitiveDateTime,) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {- let payment_processor_token = get_invoice_payment_processor_token(payment_intent);+ let invoice_token = get_invoice_payment_processor_token(payment_intent);let payment_processor_tokens_details =RedisTokenManager::get_payment_processor_metadata_for_connector_customer(@@ -1138,46 +1187,46 @@ async fn get_token_availability_for_schedule_time(errors::RedisError::RedisConnectionError.into(),))?;- // Get the token info from redis- let payment_processor_tokens_details_with_retry_info = payment_processor_token- .as_ref()- .and_then(|token| payment_processor_tokens_details.get(token));+ let payment_processor_token_response = match card_selection::pick_card_for_retry_time(+ card_selection,+ &payment_processor_tokens_details,+ invoice_token.as_deref(),+ ) {+ CardAvailability::Ready {+ payment_processor_token,+ } => PaymentProcessorTokenResponse::ScheduledTime {+ scheduled_time,+ payment_processor_token,+ },+ CardAvailability::WaitHours(retry_wait_time_hours) => {+ let utc_schedule_time: time::OffsetDateTime = common_utils::date_time::now()+ .assume_utc()+ + time::Duration::hours(retry_wait_time_hours);+ let next_available_time =+ time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());- // If payment_processor_tokens_details_with_retry_info is None, then no schedule time- let payment_processor_token_response = match payment_processor_tokens_details_with_retry_info {- None => {+ PaymentProcessorTokenResponse::NextAvailableTime {+ next_available_time,+ }+ }+ CardAvailability::HardDecline => PaymentProcessorTokenResponse::HardDecline,+ CardAvailability::NoCard => {logger::debug!("No payment processor token found for retry");PaymentProcessorTokenResponse::None}- Some(payment_token) => {- if payment_token.token_status.is_hard_decline.unwrap_or(false) {- PaymentProcessorTokenResponse::HardDecline- } else if payment_token.retry_wait_time_hours > 0 {- let utc_schedule_time: time::OffsetDateTime = common_utils::date_time::now()- .assume_utc()- + time::Duration::hours(payment_token.retry_wait_time_hours);- let next_available_time = time::PrimitiveDateTime::new(- utc_schedule_time.date(),- utc_schedule_time.time(),- );-- PaymentProcessorTokenResponse::NextAvailableTime {- next_available_time,- }- } else {- PaymentProcessorTokenResponse::ScheduledTime { scheduled_time }- }- }};Ok(payment_processor_token_response)}+/// The decider's path: the customer's invoices take turns under the customer lock, and the lock+/// holder asks the decider for a time on every card the selection admits.#[cfg(feature = "v2")]pub async fn get_best_psp_token_available_for_smart_retry(state: &SessionState,connector_customer_id: &str,payment_intent: &PaymentIntent,+ card_selection: CardSelection,) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {// Lock using payment_idlet locked_acquired = RedisTokenManager::lock_connector_customer_status(@@ -1196,11 +1245,14 @@ pub async fn get_best_psp_token_available_for_smart_retry(state,payment_intent,connector_customer_id,+ card_selection,).await?;Ok(payment_processor_token_response)}(false, _) => {+ let invoice_token = get_invoice_payment_processor_token(payment_intent);+let token_details =RedisTokenManager::get_payment_processor_metadata_for_connector_customer(state,@@ -1216,10 +1268,17 @@ pub async fn get_best_psp_token_available_for_smart_retry(.values().find(|info| info.token_status.scheduled_at.is_some());- // Check for hard decline if info is none- let hard_decline_status = token_details- .values()- .all(|token| token.token_status.is_hard_decline.unwrap_or(false));+ // Check for hard decline if info is none. No admitted card at all is not a hard+ // decline, the same as on the lock holder's path.+ let mut admitted_tokens = token_details+ .iter()+ .filter(|(token_id, token)| {+ card_selection.admits(token_id, &token.token_status, invoice_token.as_deref())+ })+ .peekable();+ let hard_decline_status = admitted_tokens.peek().is_some()+ && admitted_tokens+ .all(|(_, token)| token.token_status.is_hard_decline.unwrap_or(false));let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;@@ -1247,7 +1306,10 @@ async fn get_payment_processor_token_by_calling_decider(state: &SessionState,payment_intent: &PaymentIntent,connector_customer_id: &str,+ card_selection: CardSelection,) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {+ let invoice_token = get_invoice_payment_processor_token(payment_intent);+// Get existing tokens from Redislet existing_tokens = RedisTokenManager::get_connector_customer_payment_processor_tokens(state,@@ -1258,12 +1320,14 @@ async fn get_payment_processor_token_by_calling_decider(errors::RedisError::RedisConnectionError.into(),))?;- let active_tokens: HashMap<_, _> = existing_tokens+ let admitted_tokens: HashMap<_, _> = existing_tokens.into_iter()- .filter(|(_, token_status)| token_status.is_active != Some(false))+ .filter(|(token_id, token_status)| {+ card_selection.admits(token_id, token_status, invoice_token.as_deref())+ }).collect();- let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &active_tokens);+ let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &admitted_tokens);let payment_processor_token_response =call_decider_for_payment_processor_tokens_select_closest_time(@@ -1518,6 +1582,7 @@ pub async fn call_decider_for_payment_processor_tokens_select_closest_time(payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {scheduled_time: token.retry_decision.retry_time,+ payment_processor_token: token.token_details.payment_processor_token,};}}