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): schedule the unretried invoices in immediate next slot (#10206)
AdityaWNL12382b41bae1
diff --git a/config/development.toml b/config/development.tomlindex c688e68a6d..1e8f947598 100644--- a/config/development.toml+++ b/config/development.toml@@ -1392,6 +1392,7 @@ job_schedule_buffer_time_in_seconds = 3600reopen_workflow_buffer_time_in_seconds = 3600max_random_schedule_delay_in_seconds = 300redis_ttl_buffer_in_seconds= 300+unretried_invoice_schedule_time_offset_seconds = 60[revenue_recovery.card_config.amex]max_retries_per_day = 20diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rsindex 4cde3bd99f..c7d1fa0b4a 100644--- a/crates/router/src/types/storage/revenue_recovery.rs+++ b/crates/router/src/types/storage/revenue_recovery.rs@@ -83,6 +83,7 @@ pub struct RecoveryTimestamp {pub reopen_workflow_buffer_time_in_seconds: i64,pub max_random_schedule_delay_in_seconds: i64,pub redis_ttl_buffer_in_seconds: i64,+ pub unretried_invoice_schedule_time_offset_seconds: i64,}impl Default for RecoveryTimestamp {@@ -93,6 +94,7 @@ impl Default for RecoveryTimestamp {reopen_workflow_buffer_time_in_seconds: 60,max_random_schedule_delay_in_seconds: 300,redis_ttl_buffer_in_seconds: 300,+ unretried_invoice_schedule_time_offset_seconds: 300,}}}diff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rsindex abca6790a9..6ab3520222 100644--- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs+++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs@@ -276,6 +276,19 @@ impl RedisTokenManager {Ok(payment_processor_token_info_map)}+ /// Find the most recent date from retry history+ pub fn find_nearest_date_from_current(+ retry_history: &HashMap<Date, i32>,+ ) -> Option<(Date, i32)> {+ let today = OffsetDateTime::now_utc().date();++ retry_history+ .iter()+ .filter(|(date, _)| **date <= today) // Only past dates + today+ .max_by_key(|(date, _)| *date) // Get the most recent+ .map(|(date, retry_count)| (*date, *retry_count))+ }+/// Update connector customer payment processor tokens or add if doesn't exist#[instrument(skip_all)]pub async fn update_or_add_connector_customer_payment_processor_tokens(diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex 097c4a7982..d08c9531dc 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -2,13 +2,17 @@use std::collections::HashMap;#[cfg(feature = "v2")]-use api_models::{enums::RevenueRecoveryAlgorithmType, payments::PaymentsGetIntentRequest};+use api_models::{+ enums::{CardNetwork, RevenueRecoveryAlgorithmType},+ payments::PaymentsGetIntentRequest,+};use common_utils::errors::CustomResult;#[cfg(feature = "v2")]use common_utils::{ext_traits::AsyncExt,ext_traits::{StringExt, ValueExt},id_type,+ pii::PhoneNumberStrategy,};#[cfg(feature = "v2")]use diesel_models::types::BillingConnectorPaymentMethodDetails;@@ -80,6 +84,8 @@ use crate::{routes::SessionState, types::storage};pub struct ExecutePcrWorkflow;#[cfg(feature = "v2")]pub const REVENUE_RECOVERY: &str = "revenue_recovery";+#[cfg(feature = "v2")]+const TOTAL_SLOTS_IN_MONTH: i32 = 720;#[async_trait::async_trait]impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow {@@ -436,6 +442,42 @@ pub(crate) async fn get_schedule_time_for_smart_retry(}}+#[cfg(feature = "v2")]+async fn should_force_schedule_due_to_missed_slots(+ state: &SessionState,+ card_network: Option<CardNetwork>,+ token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,+) -> CustomResult<bool, StorageError> {+ // Check monthly retry remaining first+ let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;++ // If no monthly retries available, don't force schedule+ if !has_monthly_retries {+ return Ok(false);+ }++ Ok(RedisTokenManager::find_nearest_date_from_current(+ &token_with_retry_info.token_status.daily_retry_history,+ )+ // Filter: only consider entries with actual retries (retry_count > 0)+ .filter(|(_, retry_count)| *retry_count > 0)+ .map(|(most_recent_date, _retry_count)| {+ let threshold_hours = TOTAL_SLOTS_IN_MONTH+ / state+ .conf+ .revenue_recovery+ .card_config+ .get_network_config(card_network.clone())+ .max_retry_count_for_thirty_day;++ // Calculate time difference since last retry and compare with threshold+ (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()+ > threshold_hours.into()+ })+ // Default to false if no valid retry history found (either none exists or all have retry_count = 0)+ .unwrap_or(false))+}+#[cfg(feature = "v2")]#[derive(Debug)]struct InternalDeciderRequest {@@ -514,6 +556,13 @@ pub struct ScheduledToken {pub schedule_time: time::PrimitiveDateTime,}+#[cfg(feature = "v2")]+#[derive(Debug)]+struct TokenProcessResult {+ scheduled_token: Option<ScheduledToken>,+ force_scheduled: bool,+}+#[cfg(feature = "v2")]pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 {let now_utc = time::OffsetDateTime::now_utc();@@ -795,7 +844,7 @@ pub async fn calculate_smart_retry_time(state: &SessionState,payment_intent: &PaymentIntent,token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,-) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {+) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {let wait_hours = token_with_retry_info.retry_wait_time_hours;let current_time = time::OffsetDateTime::now_utc();let future_time = current_time + time::Duration::hours(wait_hours);@@ -806,13 +855,57 @@ pub async fn calculate_smart_retry_time(nanos: 0,});- get_schedule_time_for_smart_retry(+ let token = token_with_retry_info+ .token_status+ .payment_processor_token_details+ .payment_processor_token+ .clone();++ let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);++ let card_info = token_with_retry_info+ .token_status+ .payment_processor_token_details+ .clone();++ let card_network = card_info.card_network.clone();++ // Check if the last retry is not done within defined slot, force the retry to next slot+ if should_force_schedule_due_to_missed_slots(state, card_network.clone(), token_with_retry_info)+ .await+ .unwrap_or(false)+ {+ let schedule_offset = state+ .conf+ .revenue_recovery+ .recovery_timestamp+ .unretried_invoice_schedule_time_offset_seconds;+ let scheduled_time =+ time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);+ logger::info!(+ "Skipping Decider call, forcing a schedule for the token:- '{:?}' to time:- {}",+ masked_token,+ scheduled_time+ );+ return Ok((+ Some(time::PrimitiveDateTime::new(+ scheduled_time.date(),+ scheduled_time.time(),+ )),+ true,+ )); // force_scheduled = true+ }++ // Normal smart retry path+ let schedule_time = get_schedule_time_for_smart_retry(state,payment_intent,future_timestamp,token_with_retry_info,)- .await+ .await?;++ Ok((schedule_time, false)) // force_scheduled = false}#[cfg(feature = "v2")]@@ -820,7 +913,7 @@ async fn process_token_for_retry(state: &SessionState,token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,payment_intent: &PaymentIntent,-) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> {+) -> Result<TokenProcessResult, errors::ProcessTrackerError> {let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;@@ -832,15 +925,22 @@ async fn process_token_for_retry("Skipping decider call due to hard decline token inserted by attempt_id: {}",inserted_by_attempt_id.get_string_repr());- Ok(None)+ Ok(TokenProcessResult {+ scheduled_token: None,+ force_scheduled: false,+ })}false => {- let schedule_time =+ let (schedule_time, force_scheduled) =calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?;- Ok(schedule_time.map(|schedule_time| ScheduledToken {- token_details: token_status.payment_processor_token_details.clone(),- schedule_time,- }))++ Ok(TokenProcessResult {+ scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {+ token_details: token_status.payment_processor_token_details.clone(),+ schedule_time,+ }),+ force_scheduled,+ })}}}@@ -882,12 +982,26 @@ pub async fn call_decider_for_payment_processor_tokens_select_closest_time(}None => {+ // Flag to track if we found a force-scheduled token+ let mut force_scheduled_found = false;+for token_with_retry_info in processor_tokens.values() {- process_token_for_retry(state, token_with_retry_info, payment_intent)- .await?- .map(|token_with_schedule_time| {- tokens_with_schedule_time.push(token_with_schedule_time)- });+ let result =+ process_token_for_retry(state, token_with_retry_info, payment_intent).await?;++ // Add the scheduled token if it exists+ if let Some(scheduled_token) = result.scheduled_token {+ tokens_with_schedule_time.push(scheduled_token);+ }++ // Check if this was force-scheduled due to missed slots+ if result.force_scheduled {+ force_scheduled_found = true;+ tracing::info!(+ "Force-scheduled token detected due to missed slots, breaking early from token processing"+ );+ break; // Stop processing remaining tokens immediately+ }}}}diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rsindex 0db72a24a1..078a6e2297 100644--- a/crates/scheduler/src/utils.rs+++ b/crates/scheduler/src/utils.rs@@ -28,6 +28,7 @@ where{let batches = divide(tasks, settings);// Safety: Assuming we won't deal with more than `u64::MAX` batches at once+ logger::info!("Adding {} batches to stream", batches.len());#[allow(clippy::as_conversions)]metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metricsfor batch in batches {