Skip to content

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

feat(revenue_recovery): add the recovery request workflow (#15208)

CHALLA NISHANTH BABU8e75ce7cce0b
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index eacb5cdd31..b81cb6e415 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -16265,6 +16265,17 @@
},
"next_retry": {
"$ref": "#/components/schemas/RecoveryNextRetry"
+ },
+ "last_recovery_request_id": {
+ "type": "string",
+ "description": "Id of the recovery request this state was last saved for, so a re-run of that request is\nrecognised.",
+ "nullable": true
+ },
+ "last_transaction_created_at": {
+ "type": "string",
+ "description": "When the transaction this state was last saved for was made. A transaction made before it is\nout of date and only recorded.",
+ "example": "2022-09-10T10:11:12.000Z",
+ "nullable": true
}
}
},
@@ -23539,6 +23550,12 @@
}
],
"nullable": true
+ },
+ "recovery_request_id": {
+ "type": "string",
+ "description": "Id of the recovery request that recorded this transaction, for a transaction the merchant\nreported on a profile whose retries it triggers.",
+ "example": "revenue_recovery_6JkQbHp7Wbq3cXUtvTqV",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 30fc8d75a0..1ab6b6fac1 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2475,6 +2475,11 @@ pub struct PaymentAttemptRevenueRecoveryData {
/// Absent when it was not reported, and on attempts recorded before this was kept.
#[schema(value_type = Option<FutureUsage>, example = "off_session")]
pub setup_future_usage: Option<common_enums::FutureUsage>,
+ /// Id of the recovery request that recorded this transaction, for a transaction the merchant
+ /// reported on a profile whose retries it triggers.
+ #[schema(value_type = Option<String>, example = "revenue_recovery_6JkQbHp7Wbq3cXUtvTqV")]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub recovery_request_id: Option<String>,
}
#[derive(
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 4c10233dd8..af6a80e873 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -12024,6 +12024,7 @@ pub enum ProcessTrackerRunner {
PaymentMethodModularForwardCompatWorkflow,
PaymentMethodModularBackwardCompatWorkflow,
PassiveRecoveryWorkflow,
+ RecoveryRequestWorkflow,
ProcessDisputeWorkflow,
DisputeListWorkflow,
InvoiceSyncflow,
diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs
index 87b99cfe44..640e882bb3 100644
--- a/crates/common_types/src/payments.rs
+++ b/crates/common_types/src/payments.rs
@@ -1198,6 +1198,19 @@ pub struct ExternalTriggerState {
pub retries_after_hard_decline: Option<u16>,
/// What the merchant was last told to do.
pub next_retry: RecoveryNextRetry,
+ /// Id of the recovery request this state was last saved for, so a re-run of that request is
+ /// recognised.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_recovery_request_id: Option<String>,
+ /// When the transaction this state was last saved for was made. A transaction made before it is
+ /// out of date and only recorded.
+ #[schema(value_type = Option<String>, example = "2022-09-10T10:11:12.000Z")]
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ with = "common_utils::custom_serde::iso8601::option"
+ )]
+ pub last_transaction_created_at: Option<PrimitiveDateTime>,
}
/// Billing Descriptor information to be sent to the payment gateway
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 7d59a8014d..f8ae71f194 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -4828,6 +4828,10 @@ pub struct PaymentAttemptRecoveryData {
/// How the payment method of this attempt's transaction is set up for future use, as reported.
/// Absent on attempts recorded before this was kept.
pub setup_future_usage: Option<common_enums::FutureUsage>,
+ /// Id of the recovery request that recorded this transaction, written with the attempt so a
+ /// re-run of that recovery request recognises it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub recovery_request_id: Option<String>,
}
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(PaymentAttemptFeatureMetadata);
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index d706a3d5cc..b55f4ebeee 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -311,4 +311,29 @@ pub mod business_status {
/// This status indicates the workflow has completed successfully when the invoice is paid
pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE";
+
+ /// A reported transaction was recorded and the next retry of its invoice is scheduled
+ pub const RECOVERY_REQUEST_RETRY_SCHEDULED: &str = "RECOVERY_REQUEST_RETRY_SCHEDULED";
+
+ /// A reported transaction was recorded and a limit of the profile stops the retries
+ pub const RECOVERY_REQUEST_LIMITS_EXHAUSTED: &str = "RECOVERY_REQUEST_LIMITS_EXHAUSTED";
+
+ /// A reported transaction was recorded and no retry follows, for a reason needing no webhook
+ pub const RECOVERY_REQUEST_NO_WEBHOOK: &str = "RECOVERY_REQUEST_NO_WEBHOOK";
+
+ /// A reported transaction made with the customer was recorded; it is not a retry
+ pub const RECOVERY_REQUEST_CUSTOMER_INITIATED: &str = "RECOVERY_REQUEST_CUSTOMER_INITIATED";
+
+ /// A reported transaction was recorded after a newer transaction of its invoice was applied
+ pub const RECOVERY_REQUEST_STALE: &str = "RECOVERY_REQUEST_STALE";
+
+ /// A reported transaction is recorded on its invoice, but not by this recovery request
+ pub const RECOVERY_REQUEST_DUPLICATE: &str = "RECOVERY_REQUEST_DUPLICATE";
+
+ /// A reported transaction was not recorded because its invoice is closed
+ pub const RECOVERY_REQUEST_INVOICE_CLOSED: &str = "RECOVERY_REQUEST_INVOICE_CLOSED";
+
+ /// A reported transaction's attempt is recorded, but its invoice does not show every attempt
+ /// recorded on it, so the recovery request is not decided and the invoice needs a manual check
+ pub const RECOVERY_REQUEST_INVOICE_OUT_OF_SYNC: &str = "RECOVERY_REQUEST_INVOICE_OUT_OF_SYNC";
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 60a6d4ed68..5af73913ad 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -1669,7 +1669,7 @@ pub struct RevenueRecoveryData {
/// A closed invoice has no next retry, whatever was last stored for it. Cancelling an invoice does
/// not touch its recovery metadata, and the state saved after a report can fail to be written.
#[cfg(feature = "v2")]
-fn get_next_retry_for_intent_status(
+pub fn get_next_retry_for_intent_status(
intent_status: common_enums::IntentStatus,
next_retry: common_types::payments::RecoveryNextRetry,
) -> common_types::payments::RecoveryNextRetry {
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index e024935665..61d895919f 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -1283,6 +1283,12 @@ impl PaymentAttempt {
.as_ref()
.and_then(|data| data.setup_future_usage)
}),
+ recovery_request_id: request.feature_metadata.as_ref().and_then(|metadata| {
+ metadata
+ .revenue_recovery
+ .as_ref()
+ .and_then(|data| data.recovery_request_id.clone())
+ }),
}
}),
};
@@ -3127,6 +3133,8 @@ pub struct PaymentAttemptRevenueRecoveryData {
pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
/// How the payment method of this attempt's transaction is set up for future use, as reported.
pub setup_future_usage: Option<common_enums::FutureUsage>,
+ /// Id of the recovery request that recorded this transaction.
+ pub recovery_request_id: Option<String>,
}
#[cfg(feature = "v2")]
@@ -3143,6 +3151,7 @@ impl From<&PaymentAttemptFeatureMetadata> for DieselPaymentAttemptFeatureMetadat
.clone(),
customer_present: recovery_data.customer_present,
setup_future_usage: recovery_data.setup_future_usage,
+ recovery_request_id: recovery_data.recovery_request_id.clone(),
});
Self { revenue_recovery }
}
@@ -3160,6 +3169,7 @@ impl From<DieselPaymentAttemptFeatureMetadata> for PaymentAttemptFeatureMetadata
.billing_connector_transaction_id,
customer_present: recovery_data.customer_present,
setup_future_usage: recovery_data.setup_future_usage,
+ recovery_request_id: recovery_data.recovery_request_id,
});
Self { revenue_recovery }
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 1bfd1dfb67..35c32fa731 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -492,11 +492,6 @@ pub enum PaymentIntentUpdate {
status: common_enums::IntentStatus,
updated_by: String,
},
- /// Update the feature metadata alone, leaving the status and everything else as it stands.
- FeatureMetadataUpdate {
- feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>,
- updated_by: String,
- },
AttemptGroupUpdate {
active_attempts_group_id: id_type::GlobalAttemptGroupId,
active_attempt_id_type: common_enums::ActiveAttemptIDType,
@@ -1070,58 +1065,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
enable_account_name_verification: None,
settlement_conclusion_applied: None,
}),
- PaymentIntentUpdate::FeatureMetadataUpdate {
- feature_metadata,
- updated_by,
- } => Ok(Self {
- status: None,
- amount_captured: None,
- active_attempt_id: None,
- active_attempt_id_type: None,
- active_attempts_group_id: None,
- prerouting_algorithm: None,
- modified_at: common_utils::date_time::now(),
- amount: None,
- currency: None,
- shipping_cost: None,
- tax_details: None,
- skip_external_tax_calculation: None,
- surcharge_applicable: None,
- surcharge_amount: None,
- tax_on_surcharge: None,
- routing_algorithm_id: None,
- capture_method: None,
- authentication_type: None,
- billing_address: None,
- shipping_address: None,
- customer_present: None,
- description: None,
- return_url: None,
- setup_future_usage: None,
- apply_mit_exemption: None,
- statement_descriptor: None,
- order_details: None,
- allowed_payment_method_types: None,
- metadata: None,
- connector_metadata: None,
- feature_metadata: *feature_metadata,
- payment_link_config: None,
- request_incremental_authorization: None,
- session_expiry: None,
- frm_metadata: None,
- request_external_three_ds_authentication: None,
- updated_by,
- force_3ds_challenge: None,
- is_iframe_redirection_enabled: None,
- enable_partial_authorization: None,
- state_metadata: None,
- profile_acquirer_id: None,
- external_surcharge_strategy: None,
- external_surcharge_applicable: None,
- enable_avs_check: None,
- enable_account_name_verification: None,
- settlement_conclusion_applied: None,
- }),
PaymentIntentUpdate::AttemptGroupUpdate {
updated_by,
active_attempts_group_id,
diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
index 6f4063eb22..09a7c80a73 100644
--- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs
+++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
@@ -347,6 +347,7 @@ impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt
charge_id: recovery.charge_id,
customer_present: recovery.customer_present,
setup_future_usage: recovery.setup_future_usage,
+ recovery_request_id: recovery.recovery_request_id,
}
}),
},
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 4c1b1187a7..340b80bd5d 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -378,6 +378,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {
Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))
}
+ storage::ProcessTrackerRunner::RecoveryRequestWorkflow => Ok(Box::new(
+ workflows::recovery_request::RecoveryRequestWorkflow,
+ )),
storage::ProcessTrackerRunner::PayoutSyncWorkFlow => {
Ok(Box::new(workflows::payout_sync::PayoutSyncWorkFlow))
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index aab0ace47c..1704ebe2f4 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -8329,6 +8329,7 @@ impl
charge_id: recovery.charge_id.clone(),
customer_present: recovery.customer_present,
setup_future_usage: recovery.setup_future_usage,
+ recovery_request_id: recovery.recovery_request_id.clone(),
}
});
Self { revenue_recovery }
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index 961a37997c..beac9ba7a7 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -1,6 +1,6 @@
pub mod api;
pub mod card_selection;
-mod external_triggers;
+pub(crate) mod external_triggers;
pub mod retry_stats;
pub mod schedule;
pub mod transformers;
@@ -66,6 +66,8 @@ use crate::{
pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW";
pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW";
pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW";
+/// Task of the recovery request workflow, which processes one transaction the merchant reported.
+pub const EXTERNAL_TRIGGER_HANDLER: &str = "EXTERNAL_TRIGGER_HANDLER";
use common_enums::enums::ProcessTrackerStatus;
#[cfg(feature = "v1")]
diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs
index 95dd2400f7..e04f265523 100644
--- a/crates/router/src/core/revenue_recovery/api.rs
+++ b/crates/router/src/core/revenue_recovery/api.rs
@@ -229,6 +229,7 @@ pub async fn record_internal_attempt_api(
common_enums::TriggeredBy::Internal,
None,
None,
+ None,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rs
index 1df0bbed1f..7e8769c4ad 100644
--- a/crates/router/src/core/revenue_recovery/external_triggers.rs
+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs
@@ -1,17 +1,29 @@
use api_models::payments::RecoveryPaymentsCreate;
+use base64::Engine;
use common_types::payments::{
ExternalTriggerState, RecoveryConnector, RecoveryConnectorDetails, RecoveryNextRetry,
RecoveryNoRetryReason, RecoveryTransactionStatus,
};
-use diesel_models::business_profile::RevenueRecoveryConfig;
-use error_stack::report;
+use common_utils::{
+ consts::{BASE64_ENGINE, BASE64_ENGINE_URL_SAFE_NO_PAD},
+ crypto::{self, Encryptable, GenerateDigest},
+ encryption::Encryption,
+ errors::CustomResult,
+ id_type, type_name,
+ types::keymanager,
+};
+use diesel_models::{business_profile::RevenueRecoveryConfig, process_tracker::business_status};
+use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
- payments::{payment_intent::PaymentIntentUpdate, PaymentIntent},
+ payments::{get_next_retry_for_intent_status, PaymentIntent, PaymentIntentData},
platform::Platform,
revenue_recovery::{RecoveryPaymentAttempt, RecoveryPaymentIntent},
+ type_encryption::{crypto_operation, CryptoOperation},
+ ApiModelToDieselModelConvertor,
};
-use hyperswitch_masking::PeekInterface;
-use router_env::logger;
+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
+use router_env::{instrument, logger, tracing};
+use scheduler::errors as sch_errors;
use time::{Duration, PrimitiveDateTime};
use super::{
@@ -25,14 +37,20 @@ use crate::{
api_locking::{LockAction, LockingInput},
configs::dimension_state::{self, DimensionsWithProcessorMerchantIdAndConnector},
errors::{self, RouterResult, StorageErrorExt},
- payments::operations::{
- payment_attempt_record::PaymentAttemptRecord, ValidateStatusForOperation,
+ payments::{
+ self,
+ operations::{
+ payment_attempt_record::PaymentAttemptRecord, ValidateStatusForOperation,
+ },
},
+ webhooks::recovery_incoming::RevenueRecoveryAttempt,
},
- routes::{app::ReqState, lock_utils, SessionState},
+ routes::{app::ReqState, lock_utils, metrics, SessionState},
types::{
- domain,
- storage::{revenue_recovery as pcr, revenue_recovery_redis_operation::RedisTokenManager},
+ api as api_types, domain,
+ storage::{
+ self, revenue_recovery as pcr, revenue_recovery_redis_operation::RedisTokenManager,
+ },
},
workflows::revenue_recovery::{self as revenue_recovery_workflow, RetryTiming},
};
@@ -198,21 +216,62 @@ async fn handle_merchant_report(
reset_card_history_after_a_charge(state, request).await;
- let payment_intent = state
- .store
- .find_payment_intent_by_id(
- &invoice.payment_id,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_storage_scheme(),
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let payment_intent = read_invoice(state, platform, profile, &invoice.payment_id).await?;
let updated_invoice = RecoveryPaymentIntent::from(&payment_intent);
if !is_merchant_initiated {
return Ok((updated_invoice, None));
}
+ let (trigger_state, assigned_ab_algorithm) = Box::pin(decide_recovery_request_retry(
+ state,
+ platform,
+ profile,
+ retry_config,
+ request,
+ &recovery_attempt,
+ &payment_intent,
+ previous_trigger_state.as_ref(),
+ is_existing_invoice,
+ is_same_card,
+ ))
+ .await;
+ let next_retry = trigger_state.next_retry;
+ if let Err(error) = save_trigger_state(
+ state,
+ platform,
+ profile,
+ payment_intent,
+ trigger_state,
+ assigned_ab_algorithm,
+ )
+ .await
+ {
+ logger::error!(?error, "Failed to save the recovery state of the invoice");
+ }
+
+ Ok((updated_invoice, Some(next_retry)))
+}
+
+/// The recovery state of an invoice after a merchant-initiated recovery request: its next retry
+/// and what the request after it needs, with the A/B arm the decision assigned. The request
+/// markers are left for the caller.
+#[allow(clippy::too_many_arguments)]
+async fn decide_recovery_request_retry(
+ state: &SessionState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ retry_config: &RevenueRecoveryConfig,
+ request: &RecoveryPaymentsCreate,
+ recovery_attempt: &RecoveryPaymentAttempt,
+ payment_intent: &PaymentIntent,
+ previous_trigger_state: Option<&ExternalTriggerState>,
+ is_existing_invoice: bool,
+ is_same_card: bool,
+) -> (
+ ExternalTriggerState,
+ Option<common_enums::RevenueRecoveryABAlgorithm>,
+) {
let dimensions = dimension_state::Dimensions::new()
.with_processor_merchant_id(payment_intent.merchant_id.clone().into())
.with_connector(common_enums::connector_enums::Connector::Custombilling);
@@ -230,18 +289,16 @@ async fn handle_merchant_report(
)
.await;
let ladder_progress = get_ladder_progress(
- previous_trigger_state.as_ref(),
+ previous_trigger_state,
is_existing_invoice,
retry_count,
max_hybrid_cascading_retry_count,
);
- let last_failure_code = get_last_failure_code(request.transaction_status, &recovery_attempt);
+ let last_failure_code = get_last_failure_code(request.transaction_status, recovery_attempt);
let card_availability =
- get_card_availability(state, request.connector_customer_id.peek(), &payment_intent).await;
+ get_card_availability(state, request.connector_customer_id.peek(), payment_intent).await;
let retries_after_hard_decline = get_retries_after_hard_decline(
- previous_trigger_state
- .as_ref()
- .and_then(|trigger_state| trigger_state.retries_after_hard_decline),
+ previous_trigger_state.and_then(|trigger_state| trigger_state.retries_after_hard_decline),
is_same_card,
matches!(card_availability, CardAvailability::HardDecline),
);
@@ -251,7 +308,7 @@ async fn handle_merchant_report(
platform,
profile,
NextRetryInputs {
- payment_intent: &payment_intent,
+ payment_intent,
dimensions: &dimensions,
retry_config,
ladder_progress: &ladder_progress,
@@ -263,24 +320,19 @@ async fn handle_merchant_report(
))
.await;
- let trigger_state = ExternalTriggerState {
- consumed_ladder_rungs: decision
- .next_ladder_progress
- .unwrap_or(ladder_progress)
- .consumed_rungs,
- retries_after_hard_decline,
- next_retry: decision.next_retry,
- };
- save_trigger_state(
- state,
- platform,
- payment_intent,
- trigger_state,
+ (
+ ExternalTriggerState {
+ consumed_ladder_rungs: decision
+ .next_ladder_progress
+ .unwrap_or(ladder_progress)
+ .consumed_rungs,
+ retries_after_hard_decline,
+ next_retry: decision.next_retry,
+ last_recovery_request_id: None,
+ last_transaction_created_at: None,
+ },
decision.assigned_ab_algorithm,
)
- .await;
-
- Ok((updated_invoice, Some(decision.next_retry)))
}
/// A charged card is healthy again, so its retry history starts over, as it does for the retries
@@ -491,43 +543,57 @@ async fn get_card_availability(
}
}
-/// Keeps what the next report of the merchant needs on the invoice. Failing here costs the next
-/// retry its cluster and ladder position, not the answer to this report.
+/// Keeps what the merchant's next recovery request needs on the invoice, through the update-intent
+/// operation. A paid or cancelled invoice has ended, so it has no next retry to keep.
async fn save_trigger_state(
state: &SessionState,
platform: &Platform,
+ profile: &domain::Profile,
payment_intent: PaymentIntent,
trigger_state: ExternalTriggerState,
assigned_ab_algorithm: Option<common_enums::RevenueRecoveryABAlgorithm>,
-) {
- let mut feature_metadata = payment_intent.feature_metadata.clone();
- if let Some(recovery_metadata) = feature_metadata
- .as_mut()
- .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.as_mut())
- {
- recovery_metadata.external_trigger_state = Some(trigger_state);
- recovery_metadata.revenue_recovery_ab_routing =
- assigned_ab_algorithm.or(recovery_metadata.revenue_recovery_ab_routing);
+) -> RouterResult<()> {
+ if matches!(
+ payment_intent.status,
+ common_enums::IntentStatus::Succeeded
+ | common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::CancelledPostCapture
+ ) {
+ return Ok(());
}
-
- let storage_scheme = platform.get_processor().get_storage_scheme();
- let intent_update = PaymentIntentUpdate::FeatureMetadataUpdate {
- feature_metadata: Box::new(feature_metadata),
- updated_by: storage_scheme.inner().to_string(),
+ let Some(mut feature_metadata) = payment_intent
+ .feature_metadata
+ .map(ApiModelToDieselModelConvertor::convert_back)
+ else {
+ return Ok(());
+ };
+ let Some(recovery_metadata) = feature_metadata.revenue_recovery.as_mut() else {
+ return Ok(());
};
+ recovery_metadata.external_trigger_state = Some(trigger_state);
+ recovery_metadata.revenue_recovery_ab_routing =
+ assigned_ab_algorithm.or(recovery_metadata.revenue_recovery_ab_routing);
- if let Err(error) = state
- .store
- .update_payment_intent(
- payment_intent,
- intent_update,
- platform.get_processor().get_key_store(),
- storage_scheme,
- )
- .await
- {
- logger::error!(?error, "Failed to save the recovery state of the invoice");
- }
+ Box::pin(payments::payments_intent_operation_core::<
+ api_types::PaymentUpdateIntent,
+ _,
+ _,
+ PaymentIntentData<api_types::PaymentUpdateIntent>,
+ >(
+ state,
+ state.get_req_state(),
+ platform.clone(),
+ profile.clone(),
+ payments::operations::PaymentUpdateIntent,
+ api_models::payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
+ feature_metadata,
+ api_models::enums::UpdateActiveAttempt::NoAction,
+ ),
+ payment_intent.id,
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ ))
+ .await
+ .map(|_| ())
}
/// Where the invoice stands on the static ladder: what the last report saved, or else a position
@@ -597,6 +663,11 @@ fn get_no_retry_reason(
) -> Option<RecoveryNoRetryReason> {
if invoice_status == common_enums::IntentStatus::Succeeded {
Some(RecoveryNoRetryReason::Recovered)
+ } else if matches!(
+ invoice_status,
+ common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture
+ ) {
+ Some(RecoveryNoRetryReason::Cancelled)
} else if retry_algorithm_type == common_enums::RevenueRecoveryAlgorithmType::Monitoring {
Some(RecoveryNoRetryReason::Monitoring)
} else if limit_checks.is_retry_budget_spent {
@@ -638,3 +709,762 @@ fn get_next_retry(
RecoveryNextRetry::scheduled(retry_count, schedule_time)
}
}
+
+/// Version of the request stored in a recovery request's tracking data.
+const RECOVERY_REQUEST_VERSION: u8 = 1;
+
+/// Seconds before a recovery request runs again after a temporary error, by how many runs have
+/// failed. They end well inside the 15 minutes after which the merchant falls back to its own
+/// retry timing.
+const RECOVERY_REQUEST_RETRY_DELAYS_IN_SECONDS: [i64; 5] = [15, 30, 60, 120, 240];
+
+/// How long after it was received a recovery request keeps waiting for its invoice's lock.
+const RECOVERY_REQUEST_LOCK_WAIT_IN_MINUTES: i64 = 10;
+
+/// Seconds between tries for an invoice lock held by another recovery request.
+const RECOVERY_REQUEST_LOCK_RETRY_IN_SECONDS: i64 = 5;
+
+/// How a recovery request ended.
+#[derive(Clone, Copy, Debug)]
+enum RecoveryRequestOutcome {
+ /// Recorded, and the next retry is scheduled.
+ RetryScheduled,
+ /// Recorded, and a limit of the profile stops the retries.
+ LimitsExhausted(RecoveryNoRetryReason),
+ /// Recorded, and no retry follows, for a reason that needs no webhook.
+ NoWebhook(RecoveryNoRetryReason),
+ /// Made with the customer, so only recorded.
+ CustomerInitiated,
+ /// A newer recovery request of the invoice was applied first, so only recorded.
+ Stale,
+ /// The transaction is recorded on the invoice, but not by this recovery request.
+ Duplicate,
+ /// The invoice is closed, so nothing is recorded.
+ InvoiceClosed,
+ /// The invoice does not show every attempt recorded on it, so nothing is decided.
+ InvoiceOutOfSync,
+}
+
+impl RecoveryRequestOutcome {
+ fn from_next_retry(next_retry: &RecoveryNextRetry) -> Self {
+ match next_retry.reason {
+ None => Self::RetryScheduled,
+ Some(
+ reason @ (RecoveryNoRetryReason::RetriesExhausted
+ | RecoveryNoRetryReason::GracePeriodExpired
+ | RecoveryNoRetryReason::HardDeclined),
+ ) => Self::LimitsExhausted(reason),
+ Some(
+ reason @ (RecoveryNoRetryReason::Recovered
+ | RecoveryNoRetryReason::Monitoring
+ | RecoveryNoRetryReason::Cancelled
+ | RecoveryNoRetryReason::BelowRetryThreshold),
+ ) => Self::NoWebhook(reason),
+ }
+ }
+
+ fn name(self) -> &'static str {
+ match self {
+ Self::RetryScheduled => "retry_scheduled",
+ Self::LimitsExhausted(_) => "limits_exhausted",
+ Self::NoWebhook(_) => "no_webhook",
+ Self::CustomerInitiated => "customer_initiated",
+ Self::Stale => "stale",
+ Self::Duplicate => "duplicate",
+ Self::InvoiceClosed => "invoice_closed",
+ Self::InvoiceOutOfSync => "invoice_out_of_sync",
+ }
+ }
+
+ fn reason(self) -> Option<RecoveryNoRetryReason> {
+ match self {
+ Self::LimitsExhausted(reason) | Self::NoWebhook(reason) => Some(reason),
+ Self::RetryScheduled
+ | Self::CustomerInitiated
+ | Self::Stale
+ | Self::Duplicate
+ | Self::InvoiceClosed
+ | Self::InvoiceOutOfSync => None,
+ }
+ }
+
+ fn business_status(self) -> &'static str {
+ match self {
+ Self::RetryScheduled => business_status::RECOVERY_REQUEST_RETRY_SCHEDULED,
+ Self::LimitsExhausted(_) => business_status::RECOVERY_REQUEST_LIMITS_EXHAUSTED,
+ Self::NoWebhook(_) => business_status::RECOVERY_REQUEST_NO_WEBHOOK,
+ Self::CustomerInitiated => business_status::RECOVERY_REQUEST_CUSTOMER_INITIATED,
+ Self::Stale => business_status::RECOVERY_REQUEST_STALE,
+ Self::Duplicate => business_status::RECOVERY_REQUEST_DUPLICATE,
+ Self::InvoiceClosed => business_status::RECOVERY_REQUEST_INVOICE_CLOSED,
+ Self::InvoiceOutOfSync => business_status::RECOVERY_REQUEST_INVOICE_OUT_OF_SYNC,
+ }
+ }
+}
+
+fn reason_name(reason: RecoveryNoRetryReason) -> &'static str {
+ match reason {
+ RecoveryNoRetryReason::Recovered => "recovered",
+ RecoveryNoRetryReason::RetriesExhausted => "retries_exhausted",
+ RecoveryNoRetryReason::GracePeriodExpired => "grace_period_expired",
+ RecoveryNoRetryReason::HardDeclined => "hard_declined",
+ RecoveryNoRetryReason::Monitoring => "monitoring",
+ RecoveryNoRetryReason::Cancelled => "cancelled",
+ RecoveryNoRetryReason::BelowRetryThreshold => "below_retry_threshold",
+ }
+}
+
+/// Queues a transaction the merchant reported, to be recorded and answered by the recovery request
+/// workflow, and returns the recovery request's id, which its job id is built from. A transaction
+/// already reported in the profile is refused, as its job id is taken, whatever became of that
+/// job. The job keeps `request_body`, the request exactly as the merchant sent it, and reads
+/// `request` back from it.
+pub(crate) async fn queue_recovery_request(
+ state: &SessionState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ request: &RecoveryPaymentsCreate,
+ request_body: &Secret<String>,
+ connector: RecoveryConnector,
+) -> RouterResult<String> {
+ let recovery_request_id = get_recovery_request_id(
+ profile.get_id(),
+ &request.merchant_reference_id,
+ &request.connector_transaction_id,
+ )?;
+ let received_at = common_utils::date_time::now();
+ let encrypted_request = encrypt_recovery_request(
+ state,
+ platform.get_processor().get_key_store(),
+ request_body,
+ )
+ .await?;
+ let tracking_data = pcr::RecoveryRequestTrackingData {
+ recovery_request_id: recovery_request_id.clone(),
+ merchant_id: platform.get_processor().get_account().get_id().clone(),
+ profile_id: profile.get_id().clone(),
+ merchant_reference_id: request.merchant_reference_id.clone(),
+ connector_transaction_id: request.connector_transaction_id.clone(),
+ connector,
+ received_at,
+ request_version: RECOVERY_REQUEST_VERSION,
+ encrypted_request,
+ };
+ let runner = storage::ProcessTrackerRunner::RecoveryRequestWorkflow;
+ let task = super::EXTERNAL_TRIGGER_HANDLER;
+ let process = storage::ProcessTrackerNew::new(
+ format!("{runner}_{task}_{recovery_request_id}"),
+ task,
+ runner,
+ ["REVENUE_RECOVERY"],
+ tracking_data,
+ None,
+ received_at,
+ common_types::consts::API_VERSION,
+ state.conf.application_source,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct the recovery request task")?;
+ state.store.insert_process(process).await.map_err(|error| {
+ if error.current_context().is_db_unique_violation() {
+ error.change_context(errors::ApiErrorResponse::GenericDuplicateError {
+ message: format!(
+ "The transaction {} is already reported for the invoice {}",
+ request.connector_transaction_id,
+ request.merchant_reference_id.get_string_repr()
+ ),
+ })
+ } else {
+ error
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to queue the recovery request")
+ }
+ })?;
+ metrics::TASKS_ADDED_COUNT.add(
+ 1,
+ router_env::metric_attributes!(("flow", "RecoveryRequest")),
+ );
+ logger::info!(
+ recovery_request_id = %recovery_request_id,
+ merchant_reference_id = %request.merchant_reference_id.get_string_repr(),
+ connector_transaction_id = %request.connector_transaction_id,
+ "Recovery request queued"
+ );
+ Ok(recovery_request_id)
+}
+
+/// The id of a recovery request, the same for every request for a transaction: the profile, the
+/// invoice and the transaction, in that order, hashed with SHA-256 so that its job id always fits
+/// the job id column.
+/// The format must not change, nor the runner and task names its job id starts with, or a
+/// transaction reported before the change could be reported again.
+fn get_recovery_request_id(
+ profile_id: &id_type::ProfileId,
+ merchant_reference_id: &id_type::PaymentReferenceId,
+ connector_transaction_id: &str,
+) -> RouterResult<String> {
+ let key = format!(
+ "{}:{}:{}",
+ profile_id.get_string_repr(),
+ merchant_reference_id.get_string_repr(),
+ connector_transaction_id
+ );
+ let digest = crypto::Sha256
+ .generate_digest(key.as_bytes())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to hash the recovery request's id")?;
+ Ok(BASE64_ENGINE_URL_SAFE_NO_PAD.encode(digest))
+}
+
+/// The request body encrypted with the merchant's key and base64 encoded.
+async fn encrypt_recovery_request(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ request_body: &Secret<String>,
+) -> RouterResult<String> {
+ let encrypted: Encryptable<Secret<String>> = crypto_operation(
+ &state.into(),
+ type_name!(pcr::RecoveryRequestTrackingData),
+ CryptoOperation::Encrypt(request_body.clone()),
+ keymanager::Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.get_inner().peek(),
+ )
+ .await
+ .and_then(|operation| operation.try_into_operation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt the recovery request")?;
+ Ok(BASE64_ENGINE.encode(encrypted.into_encrypted().peek()))
+}
+
+/// The stored request decrypted, as JSON.
+async fn decrypt_recovery_request(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ encrypted_request: Vec<u8>,
+) -> RouterResult<String> {
+ let decrypted: Encryptable<Secret<String>> = crypto_operation(
+ &state.into(),
+ type_name!(pcr::RecoveryRequestTrackingData),
+ CryptoOperation::Decrypt(Encryption::new(Secret::new(encrypted_request))),
+ keymanager::Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.get_inner().peek(),
+ )
+ .await
+ .and_then(|operation| operation.try_into_operation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to decrypt the recovery request")?;
+ Ok(decrypted.into_inner().expose())
+}
+
+/// Records a transaction the merchant reported and decides the next retry of its invoice. Called by
+/// the recovery request workflow: every outcome finishes the job here, apart from a wait for the
+/// invoice's lock, which puts the job back in the queue, and only a temporary error is returned, for
+/// the workflow to run the recovery request again.
+#[instrument(
+ skip_all,
+ fields(
+ process_id = %process.id,
+ recovery_request_id = %tracking_data.recovery_request_id,
+ merchant_id = %tracking_data.merchant_id.get_string_repr(),
+ profile_id = %tracking_data.profile_id.get_string_repr(),
+ merchant_reference_id = %tracking_data.merchant_reference_id.get_string_repr(),
+ connector_transaction_id = %tracking_data.connector_transaction_id,
+ payment_id = tracing::field::Empty,
+ attempt_id = tracing::field::Empty,
+ )
+)]
+pub(crate) async fn process_recovery_request(
+ state: &SessionState,
+ process: &storage::ProcessTracker,
+ tracking_data: pcr::RecoveryRequestTrackingData,
+) -> Result<(), sch_errors::ProcessTrackerError> {
+ let now = common_utils::date_time::now();
+ if tracking_data.request_version != RECOVERY_REQUEST_VERSION {
+ logger::error!(
+ request_version = tracking_data.request_version,
+ "The stored recovery request has a version this release does not read"
+ );
+ return finish_unreadable_recovery_request(state, process).await;
+ }
+ let Ok(encrypted_request) = BASE64_ENGINE.decode(&tracking_data.encrypted_request) else {
+ logger::error!("The stored recovery request is not base64");
+ return finish_unreadable_recovery_request(state, process).await;
+ };
+
+ let (platform, profile) = load_recovery_request_context(state, &tracking_data)
+ .await
+ .map_err(|error| recovery_request_step_failed("load", error))?;
+ let body = decrypt_recovery_request(
+ state,
+ platform.get_processor().get_key_store(),
+ encrypted_request,
+ )
+ .await
+ .map_err(|error| recovery_request_step_failed("decrypt", error))?;
+ let request = match serde_json::from_str::<RecoveryPaymentsCreate>(&body) {
+ Ok(request) => request,
+ // Logged without its message, which can quote a value from the body.
+ Err(error) => {
+ logger::error!(
+ category = ?error.classify(),
+ line = error.line(),
+ column = error.column(),
+ "The stored recovery request cannot be read"
+ );
+ return finish_unreadable_recovery_request(state, process).await;
+ }
+ };
+ let Some(retry_config) = profile.revenue_recovery_config.clone() else {
+ logger::error!(
+ "The profile has no revenue recovery config, so the recovery request cannot be applied"
+ );
+ return finish_failed_recovery_request(state, process).await;
+ };
+ // A value sent in the request takes priority over the one on the profile.
+ let request = RecoveryPaymentsCreate {
+ enable_partial_authorization: request
+ .enable_partial_authorization
+ .or(Some(retry_config.enable_partial_authorization.into())),
+ ..request
+ };
+
+ let merchant_id = tracking_data.merchant_id.clone();
+ let invoice_lock = LockAction::Hold {
+ input: LockingInput {
+ unique_locking_key: tracking_data
+ .merchant_reference_id
+ .get_string_repr()
+ .to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::Payments,
+ override_lock_retries: Some(1),
+ },
+ };
+ if let Err(error) = invoice_lock
+ .clone()
+ .perform_locking_action(state, merchant_id.clone())
+ .await
+ {
+ return match error.current_context() {
+ errors::ApiErrorResponse::ResourceBusy => {
+ wait_for_invoice_lock(state, process, &tracking_data, now).await
+ }
+ _ => Err(recovery_request_step_failed("lock", error)),
+ };
+ }
+ if process.retry_count == 0 {
+ metrics::REVENUE_RECOVERY_REQUEST_QUEUE_DELAY
+ .record((now - tracking_data.received_at).as_seconds_f64(), &[]);
+ }
+
+ let outcome = Box::pin(apply_recovery_request(
+ state,
+ &tracking_data,
+ &platform,
+ &profile,
+ &request,
+ &retry_config,
+ ))
+ .await;
+ if let Err(error) = invoice_lock.free_lock_action(state, merchant_id).await {
+ logger::error!(?error, "Failed to release the lock of the invoice");
+ }
+ finish_recovery_request(state, process, outcome?).await
+}
+
+/// The merchant and profile of a recovery request, and the platform to act as, with the merchant's
+/// API key as the initiator, as when the API acted on the request itself.
+async fn load_recovery_request_context(
+ state: &SessionState,
+ tracking_data: &pcr::RecoveryRequestTrackingData,
+) -> error_stack::Result<(Platform, domain::Profile), errors::StorageError> {
+ let db = &*state.store;
+ let key_store = db
+ .get_merchant_key_store_by_merchant_id(
+ &tracking_data.merchant_id,
+ &db.get_master_key().to_vec().into(),
+ )
+ .await?;
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
+ .await?;
+ let profile = db
+ .find_business_profile_by_profile_id(&key_store, &tracking_data.profile_id)
+ .await?;
+ let initiator = domain::Initiator::Api {
+ merchant_id: merchant_account.get_id().clone(),
+ merchant_account_type: merchant_account.merchant_account_type,
+ publishable_key: merchant_account.publishable_key.clone(),
+ };
+ let platform = Platform::new(
+ merchant_account.clone(),
+ key_store.clone(),
+ merchant_account,
+ key_store,
+ Some(initiator),
+ );
+ Ok((platform, profile))
+}
+
+/// Records the reported transaction and decides the next retry, under the invoice's lock. An error
+/// is temporary, and the recovery request runs again.
+async fn apply_recovery_request(
+ state: &SessionState,
+ tracking_data: &pcr::RecoveryRequestTrackingData,
+ platform: &Platform,
+ profile: &domain::Profile,
+ request: &RecoveryPaymentsCreate,
+ retry_config: &RevenueRecoveryConfig,
+) -> Result<RecoveryRequestOutcome, sch_errors::ProcessTrackerError> {
+ let req_state = state.get_req_state();
+ let invoice = api::get_or_create_invoice(state, &req_state, platform, profile, request)
+ .await
+ .map_err(|error| recovery_request_step_failed("invoice", error))?;
+ tracing::Span::current().record("payment_id", invoice.payment_id.get_string_repr());
+
+ let previous_recovery_metadata = invoice
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref());
+ let previous_trigger_state = previous_recovery_metadata
+ .and_then(|recovery_metadata| recovery_metadata.external_trigger_state.clone());
+ let recovery_request_id = tracking_data.recovery_request_id.as_str();
+
+ let attempts = RevenueRecoveryAttempt::find_recovery_request_attempt(
+ request, state, &req_state, platform, profile, &invoice,
+ )
+ .await
+ .map_err(|error| recovery_request_step_failed("record", error))?;
+ let recovery_attempt = match attempts.recorded {
+ Some(attempt) => {
+ tracing::Span::current().record("attempt_id", attempt.attempt_id.get_string_repr());
+ let recorded_by = attempt
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref())
+ .and_then(|recovery_data| recovery_data.recovery_request_id.as_deref());
+ if recorded_by != Some(recovery_request_id) {
+ return Ok(RecoveryRequestOutcome::Duplicate);
+ }
+ if let Some(saved_state) = previous_trigger_state.as_ref().filter(|trigger_state| {
+ trigger_state.last_recovery_request_id.as_deref() == Some(recovery_request_id)
+ }) {
+ return Ok(RecoveryRequestOutcome::from_next_retry(
+ &get_next_retry_for_intent_status(invoice.status, saved_state.next_retry),
+ ));
+ }
+ let recorded_on_invoice = previous_recovery_metadata
+ .map(|recovery_metadata| usize::from(recovery_metadata.total_retry_count));
+ if recorded_on_invoice != Some(attempts.total) {
+ logger::error!(
+ ?recorded_on_invoice,
+ attempts = ?attempts.total,
+ "The invoice does not show every attempt recorded on it"
+ );
+ return Ok(RecoveryRequestOutcome::InvoiceOutOfSync);
+ }
+ attempt
+ }
+ None => {
+ if PaymentAttemptRecord
+ .validate_status_for_operation(invoice.status)
+ .is_err()
+ {
+ return Ok(RecoveryRequestOutcome::InvoiceClosed);
+ }
+ let attempt = RevenueRecoveryAttempt::record_recovery_request_attempt(
+ request,
+ state,
+ &req_state,
+ platform,
+ profile,
+ &invoice,
+ &RecoveryConnectorDetails::ReportedByMerchant {
+ connector: tracking_data.connector.into(),
+ },
+ tracking_data.recovery_request_id.clone(),
+ )
+ .await
+ .map_err(|error| recovery_request_step_failed("record", error))?;
+ tracing::Span::current().record("attempt_id", attempt.attempt_id.get_string_repr());
+ attempt
+ }
+ };
+
+ reset_card_history_after_a_charge(state, request).await;
+
+ if !is_merchant_initiated(request) {
+ return Ok(RecoveryRequestOutcome::CustomerInitiated);
+ }
+ if let Some(last_transaction_created_at) = previous_trigger_state
+ .as_ref()
+ .and_then(|trigger_state| trigger_state.last_transaction_created_at)
+ .filter(|last_transaction_created_at| {
+ *last_transaction_created_at > request.transaction_created_at
+ })
+ {
+ logger::error!(
+ ?last_transaction_created_at,
+ transaction_created_at = ?request.transaction_created_at,
+ "The invoice was last decided on a newer transaction, so this one is only recorded"
+ );
+ return Ok(RecoveryRequestOutcome::Stale);
+ }
+
+ let is_existing_invoice = attempts.earlier > 0;
+ let is_same_card = attempts.previous_card.as_ref()
+ == Some(
+ request
+ .payment_method_data
+ .primary_processor_payment_method_token
+ .peek(),
+ );
+ let payment_intent = read_invoice(state, platform, profile, &invoice.payment_id)
+ .await
+ .map_err(|error| recovery_request_step_failed("invoice", error))?;
+ let (trigger_state, assigned_ab_algorithm) = Box::pin(decide_recovery_request_retry(
+ state,
+ platform,
+ profile,
+ retry_config,
+ request,
+ &recovery_attempt,
+ &payment_intent,
+ previous_trigger_state.as_ref(),
+ is_existing_invoice,
+ is_same_card,
+ ))
+ .await;
+ let next_retry = trigger_state.next_retry;
+ let trigger_state = ExternalTriggerState {
+ last_recovery_request_id: Some(tracking_data.recovery_request_id.clone()),
+ last_transaction_created_at: Some(request.transaction_created_at),
+ ..trigger_state
+ };
+ save_trigger_state(
+ state,
+ platform,
+ profile,
+ payment_intent,
+ trigger_state,
+ assigned_ab_algorithm,
+ )
+ .await
+ .map_err(|error| recovery_request_step_failed("save_state", error))?;
+
+ logger::info!(
+ retry_count = next_retry.retry_count,
+ schedule_time = ?next_retry.schedule_time,
+ reason = ?next_retry.reason,
+ "Next retry of the invoice decided"
+ );
+ Ok(RecoveryRequestOutcome::from_next_retry(&next_retry))
+}
+
+/// Only a transaction made off session with the customer absent is merchant initiated. A request
+/// that leaves either out gets the defaults the invoice is created with.
+fn is_merchant_initiated(request: &RecoveryPaymentsCreate) -> bool {
+ request
+ .customer_present
+ .unwrap_or(common_enums::PresenceOfCustomerDuringPayment::Absent)
+ == common_enums::PresenceOfCustomerDuringPayment::Absent
+ && request
+ .setup_future_usage
+ .unwrap_or(common_enums::FutureUsage::OffSession)
+ .is_off_session()
+}
+
+/// The invoice as it is now, read through the get intent operation.
+async fn read_invoice(
+ state: &SessionState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ payment_id: &id_type::GlobalPaymentId,
+) -> RouterResult<PaymentIntent> {
+ let (payment_data, _, _) = Box::pin(payments::payments_intent_operation_core::<
+ api_types::PaymentGetIntent,
+ _,
+ _,
+ PaymentIntentData<api_types::PaymentGetIntent>,
+ >(
+ state,
+ state.get_req_state(),
+ platform.clone(),
+ profile.clone(),
+ payments::operations::PaymentGetIntent,
+ api_models::payments::PaymentsGetIntentRequest {
+ id: payment_id.clone(),
+ },
+ payment_id.clone(),
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ ))
+ .await?;
+ Ok(payment_data.payment_intent)
+}
+
+/// Puts a recovery request back in the queue while another request of its invoice holds the lock,
+/// without spending its retries, until the wait runs out.
+async fn wait_for_invoice_lock(
+ state: &SessionState,
+ process: &storage::ProcessTracker,
+ tracking_data: &pcr::RecoveryRequestTrackingData,
+ now: PrimitiveDateTime,
+) -> Result<(), sch_errors::ProcessTrackerError> {
+ if now < tracking_data.received_at + Duration::minutes(RECOVERY_REQUEST_LOCK_WAIT_IN_MINUTES) {
+ logger::info!("The invoice is held by another recovery request; trying again shortly");
+ state
+ .store
+ .as_scheduler()
+ .update_process(
+ process.clone(),
+ storage::ProcessTrackerUpdate::StatusRetryUpdate {
+ status: common_enums::ProcessTrackerStatus::Pending,
+ retry_count: process.retry_count,
+ schedule_time: now + Duration::seconds(RECOVERY_REQUEST_LOCK_RETRY_IN_SECONDS),
+ },
+ )
+ .await?;
+ return Ok(());
+ }
+ metrics::REVENUE_RECOVERY_REQUEST_STEP_FAILED
+ .add(1, router_env::metric_attributes!(("step", "lock")));
+ logger::error!("The invoice stayed held by another recovery request for too long");
+ state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(process.clone(), business_status::RETRIES_EXCEEDED)
+ .await?;
+ record_recovery_request_outcome("retries_exceeded", None);
+ Ok(())
+}
+
+/// Finishes a recovery request's job with its outcome, counting and logging it.
+async fn finish_recovery_request(
+ state: &SessionState,
+ process: &storage::ProcessTracker,
+ outcome: RecoveryRequestOutcome,
+) -> Result<(), sch_errors::ProcessTrackerError> {
+ state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(process.clone(), outcome.business_status())
+ .await?;
+ record_recovery_request_outcome(outcome.name(), outcome.reason());
+ match outcome {
+ RecoveryRequestOutcome::Stale
+ | RecoveryRequestOutcome::Duplicate
+ | RecoveryRequestOutcome::InvoiceClosed => {
+ logger::warn!(
+ outcome = outcome.name(),
+ "Recovery request ended without a decision"
+ )
+ }
+ RecoveryRequestOutcome::InvoiceOutOfSync => logger::error!(
+ outcome = outcome.name(),
+ "Recovery request not decided, as its invoice does not show every attempt recorded on \
+ it; the invoice needs a manual check"
+ ),
+ RecoveryRequestOutcome::RetryScheduled
+ | RecoveryRequestOutcome::LimitsExhausted(_)
+ | RecoveryRequestOutcome::NoWebhook(_)
+ | RecoveryRequestOutcome::CustomerInitiated => logger::info!(
+ outcome = outcome.name(),
+ reason = ?outcome.reason(),
+ "Recovery request processed"
+ ),
+ }
+ Ok(())
+}
+
+/// Ends a recovery request whose stored body cannot be read, which no later run can read either.
+async fn finish_unreadable_recovery_request(
+ state: &SessionState,
+ process: &storage::ProcessTracker,
+) -> Result<(), sch_errors::ProcessTrackerError> {
+ metrics::REVENUE_RECOVERY_REQUEST_STEP_FAILED
+ .add(1, router_env::metric_attributes!(("step", "decode")));
+ finish_failed_recovery_request(state, process).await
+}
+
+/// Ends a recovery request's job for good, for an error a later run would hit again.
+pub(crate) async fn finish_failed_recovery_request(
+ state: &SessionState,
+ process: &storage::ProcessTracker,
+) -> Result<(), sch_errors::ProcessTrackerError> {
+ state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(process.clone(), business_status::FAILURE)
+ .await?;
+ record_recovery_request_outcome("failed", None);
+ Ok(())
+}
+
+/// Runs a recovery request again after a temporary error, sooner first, until its retries run out.
+pub(crate) async fn retry_recovery_request(
+ state: &SessionState,
+ process: storage::ProcessTracker,
+ error: sch_errors::ProcessTrackerError,
+) -> CustomResult<(), sch_errors::ProcessTrackerError> {
+ let delay_in_seconds = usize::try_from(process.retry_count)
+ .ok()
+ .and_then(|failed_runs| {
+ RECOVERY_REQUEST_RETRY_DELAYS_IN_SECONDS
+ .get(failed_runs)
+ .copied()
+ });
+ match delay_in_seconds {
+ Some(delay_in_seconds) => {
+ logger::warn!(
+ ?error,
+ retry_count = process.retry_count,
+ delay_in_seconds,
+ "Recovery request failed; running it again"
+ );
+ state
+ .store
+ .as_scheduler()
+ .retry_process(
+ process,
+ common_utils::date_time::now() + Duration::seconds(delay_in_seconds),
+ )
+ .await
+ .change_context(sch_errors::ProcessTrackerError::ProcessUpdateFailed)
+ }
+ None => {
+ logger::error!(
+ ?error,
+ retry_count = process.retry_count,
+ "Recovery request failed and has no retries left"
+ );
+ state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED)
+ .await
+ .change_context(sch_errors::ProcessTrackerError::ProcessUpdateFailed)?;
+ record_recovery_request_outcome("retries_exceeded", None);
+ Ok(())
+ }
+ }
+}
+
+fn record_recovery_request_outcome(outcome: &'static str, reason: Option<RecoveryNoRetryReason>) {
+ metrics::REVENUE_RECOVERY_REQUEST_OUTCOME.add(
+ 1,
+ router_env::metric_attributes!(
+ ("outcome", outcome),
+ ("reason", reason.map_or("none", reason_name))
+ ),
+ );
+}
+
+/// Counts and logs a temporary error in a step of a recovery request, for it to run again.
+fn recovery_request_step_failed<E: std::fmt::Debug>(
+ step: &'static str,
+ error: error_stack::Report<E>,
+) -> sch_errors::ProcessTrackerError {
+ metrics::REVENUE_RECOVERY_REQUEST_STEP_FAILED
+ .add(1, router_env::metric_attributes!(("step", step)));
+ logger::error!(?error, step, "A step of the recovery request failed");
+ sch_errors::ProcessTrackerError::FlowExecutionError { flow: step }
+}
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index cc2bf6d23d..b4e8883273 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -303,6 +303,19 @@ async fn handle_schedule_failed_payment(
#[derive(Debug)]
pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData);
+
+/// The attempts of an invoice, as the transaction of a recovery request sees them.
+#[cfg(feature = "v2")]
+pub struct RecoveryRequestAttempts {
+ /// The attempt that recorded the transaction, once it is recorded.
+ pub recorded: Option<revenue_recovery::RecoveryPaymentAttempt>,
+ /// How many attempts were recorded on the invoice before the transaction's.
+ pub earlier: usize,
+ /// The processor token of the card of the last attempt recorded before the transaction's.
+ pub previous_card: Option<String>,
+ /// How many attempts the invoice has.
+ pub total: usize,
+}
#[derive(Debug)]
pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData);
@@ -513,10 +526,83 @@ impl RevenueRecoveryAttempt {
connector_details,
data.customer_present,
data.setup_future_usage,
+ None,
)
.await
}
+ /// What the attempts of the invoice say about the transaction of a recovery request: the
+ /// attempt that recorded it, if any, so the caller can tell whether this request recorded it on
+ /// an earlier run or another request did, and the attempts recorded before it.
+ pub async fn find_recovery_request_attempt(
+ data: &api_models::payments::RecoveryPaymentsCreate,
+ state: &SessionState,
+ req_state: &ReqState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_intent: &revenue_recovery::RecoveryPaymentIntent,
+ ) -> CustomResult<RecoveryRequestAttempts, errors::RevenueRecoveryError> {
+ let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(
+ data,
+ ));
+ let attempts =
+ Self::list_attempts(state, req_state, platform, profile, payment_intent).await?;
+ let listed = recovery_attempt.find_listed_attempt(&attempts);
+ let recorded_at = listed.as_ref().map(|attempt| attempt.created_at);
+ let earlier: Vec<&api_payments::PaymentAttemptResponse> = attempts
+ .payment_attempt_list
+ .iter()
+ .filter(|attempt| {
+ recorded_at.is_none_or(|recorded_at| attempt.created_at < recorded_at)
+ })
+ .collect();
+ let previous_card = earlier
+ .iter()
+ .max_by_key(|attempt| attempt.created_at)
+ .and_then(|attempt| attempt.payment_token.clone());
+ let recorded = match listed {
+ Some(attempt) => Some(recovery_attempt.to_recovery_attempt(state, attempt).await),
+ None => None,
+ };
+ Ok(RecoveryRequestAttempts {
+ recorded,
+ earlier: earlier.len(),
+ previous_card,
+ total: attempts.payment_attempt_list.len(),
+ })
+ }
+
+ /// Records the transaction of a recovery request, with the request's id on the attempt.
+ /// The caller has checked under the invoice's lock that it is not recorded yet.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn record_recovery_request_attempt(
+ data: &api_models::payments::RecoveryPaymentsCreate,
+ state: &SessionState,
+ req_state: &ReqState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_intent: &revenue_recovery::RecoveryPaymentIntent,
+ connector_details: &common_types::payments::RecoveryConnectorDetails,
+ recovery_request_id: String,
+ ) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> {
+ let (recorded_attempt, _) = Self(
+ revenue_recovery::RevenueRecoveryAttemptData::foreign_from(data),
+ )
+ .record_payment_attempt(
+ state,
+ req_state,
+ platform,
+ profile,
+ payment_intent,
+ connector_details,
+ data.customer_present,
+ data.setup_future_usage,
+ Some(recovery_request_id),
+ )
+ .await?;
+ Ok(recorded_attempt)
+ }
+
fn get_recovery_invoice_transaction_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
@@ -617,6 +703,24 @@ impl RevenueRecoveryAttempt {
)>,
errors::RevenueRecoveryError,
> {
+ let attempts =
+ Self::list_attempts(state, req_state, platform, profile, payment_intent).await?;
+ let payment_attempt = match self.find_listed_attempt(&attempts) {
+ Some(attempt) => Some(self.to_recovery_attempt(state, attempt).await),
+ None => None,
+ };
+ // If we have an attempt, combine it with payment_intent in a tuple.
+ Ok(payment_attempt.map(|attempt| (attempt, (*payment_intent).clone())))
+ }
+
+ /// The attempts of the invoice, through the list attempts operation.
+ async fn list_attempts(
+ state: &SessionState,
+ req_state: &ReqState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_intent: &revenue_recovery::RecoveryPaymentIntent,
+ ) -> CustomResult<api_payments::PaymentAttemptListResponse, errors::RevenueRecoveryError> {
let attempt_response =
Box::pin(payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
@@ -639,65 +743,9 @@ impl RevenueRecoveryAttempt {
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
- let response = match attempt_response {
+ match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
- let final_attempt = self
- .0
- .charge_id
- .as_ref()
- .map(|charge_id| {
- payments_response
- .find_attempt_in_attempts_list_using_charge_id(charge_id.clone())
- })
- .unwrap_or_else(|| {
- self.0
- .connector_transaction_id
- .as_ref()
- .and_then(|transaction_id| {
- payments_response
- .find_attempt_in_attempts_list_using_connector_transaction_id(
- transaction_id,
- )
- })
- });
- let payment_attempt = match final_attempt {
- Some(res) => {
- let standardised_error_code =
- retry_stats::events::resolve_standardised_error_code(
- state,
- res.connector.clone(),
- res.error.as_ref().map(|e| e.code.clone()),
- res.error.as_ref().map(|e| e.message.clone()),
- res.error
- .as_ref()
- .and_then(|e| e.network_decline_code.clone()),
- self.0.card_info.card_network.clone(),
- )
- .await;
- Some(revenue_recovery::RecoveryPaymentAttempt {
- attempt_id: res.id.to_owned(),
- attempt_status: res.status.to_owned(),
- feature_metadata: res.feature_metadata.to_owned(),
- amount: res.amount.net_amount,
- network_advice_code: res
- .error
- .clone()
- .and_then(|e| e.network_advice_code), // Placeholder, to be populated if available
- network_decline_code: res
- .error
- .clone()
- .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available
- error_code: res.error.clone().map(|error| error.code),
- created_at: res.created_at,
- standardised_error_code,
- })
- }
- None => None,
- };
- // If we have an attempt, combine it with payment_intent in a tuple.
- let res_with_payment_intent_and_attempt =
- payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));
- Ok(res_with_payment_intent_and_attempt)
+ Ok(payments_response)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
@@ -706,8 +754,61 @@ impl RevenueRecoveryAttempt {
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to fetch payment attempt in recovery webhook flow")
}
- }?;
- Ok(response)
+ }
+ }
+
+ /// This transaction's attempt among the invoice's attempts, found by its charge id when it has
+ /// one, and otherwise by its connector transaction id.
+ fn find_listed_attempt(
+ &self,
+ attempts: &api_payments::PaymentAttemptListResponse,
+ ) -> Option<api_payments::PaymentAttemptResponse> {
+ self.0
+ .charge_id
+ .as_ref()
+ .map(|charge_id| {
+ attempts.find_attempt_in_attempts_list_using_charge_id(charge_id.clone())
+ })
+ .unwrap_or_else(|| {
+ self.0
+ .connector_transaction_id
+ .as_ref()
+ .and_then(|transaction_id| {
+ attempts.find_attempt_in_attempts_list_using_connector_transaction_id(
+ transaction_id,
+ )
+ })
+ })
+ }
+
+ /// The attempt as revenue recovery reads it, with its standardised error code.
+ async fn to_recovery_attempt(
+ &self,
+ state: &SessionState,
+ res: api_payments::PaymentAttemptResponse,
+ ) -> revenue_recovery::RecoveryPaymentAttempt {
+ let standardised_error_code = retry_stats::events::resolve_standardised_error_code(
+ state,
+ res.connector.clone(),
+ res.error.as_ref().map(|e| e.code.clone()),
+ res.error.as_ref().map(|e| e.message.clone()),
+ res.error
+ .as_ref()
+ .and_then(|e| e.network_decline_code.clone()),
+ self.0.card_info.card_network.clone(),
+ )
+ .await;
+ revenue_recovery::RecoveryPaymentAttempt {
+ attempt_id: res.id.to_owned(),
+ attempt_status: res.status.to_owned(),
+ feature_metadata: res.feature_metadata.to_owned(),
+ amount: res.amount.net_amount,
+ network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available
+ network_decline_code: res.error.clone().and_then(|e| e.network_decline_code), // Placeholder, to be populated if available
+ error_code: res.error.clone().map(|error| error.code),
+ created_at: res.created_at,
+ standardised_error_code,
+ }
}
#[allow(clippy::too_many_arguments)]
@@ -721,6 +822,7 @@ impl RevenueRecoveryAttempt {
connector_details: &common_types::payments::RecoveryConnectorDetails,
customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
setup_future_usage: Option<common_enums::FutureUsage>,
+ recovery_request_id: Option<String>,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
@@ -735,6 +837,7 @@ impl RevenueRecoveryAttempt {
common_enums::TriggeredBy::External,
customer_present,
setup_future_usage,
+ recovery_request_id,
)
.await?;
let attempt_response = Box::pin(payments::record_attempt_core(
@@ -869,6 +972,7 @@ impl RevenueRecoveryAttempt {
triggered_by: common_enums::TriggeredBy,
customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
setup_future_usage: Option<common_enums::FutureUsage>,
+ recovery_request_id: Option<String>,
) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError>
{
let revenue_recovery_attempt_data = &self.0;
@@ -881,6 +985,7 @@ impl RevenueRecoveryAttempt {
charge_id: self.0.charge_id.clone(),
customer_present,
setup_future_usage,
+ recovery_request_id,
}),
};
@@ -1055,6 +1160,7 @@ impl RevenueRecoveryAttempt {
),
None,
None,
+ None,
)
.await
})
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 384a24b26b..29887afe71 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -382,6 +382,35 @@ counter_metric!(
unit: "1",
);
+counter_metric!(
+ REVENUE_RECOVERY_REQUEST_OUTCOME,
+ GLOBAL_METER,
+ name: "revenue_recovery.recovery_request.outcome",
+ description: "Recovery requests by how their workflow ended (retry_scheduled, \
+ limits_exhausted, no_webhook, customer_initiated, stale, duplicate, \
+ invoice_closed, retries_exceeded, failed), with the next retry `reason`",
+ unit: "1",
+);
+counter_metric!(
+ REVENUE_RECOVERY_REQUEST_STEP_FAILED,
+ GLOBAL_METER,
+ name: "revenue_recovery.recovery_request.step_failed",
+ description: "Errors in a step of the recovery request workflow, by `step`, before the job is \
+ retried or ended",
+ unit: "1",
+);
+histogram_metric_f64!(
+ REVENUE_RECOVERY_REQUEST_QUEUE_DELAY,
+ GLOBAL_METER,
+ name: "revenue_recovery.recovery_request.queue_delay",
+ description: "Seconds from the API accepting a recovery request to the run of its workflow \
+ that takes the invoice's lock, so any wait for the lock is included",
+ unit: "s",
+ boundaries: vec![
+ 1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0, 1800.0, 3600.0
+ ],
+);
+
// Analytics reports generated by the process tracker
counter_metric!(
ANALYTICS_REPORTS_DELIVERED,
diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs
index 2aef53f842..6fcc321533 100644
--- a/crates/router/src/types/storage/revenue_recovery.rs
+++ b/crates/router/src/types/storage/revenue_recovery.rs
@@ -17,6 +17,29 @@ use crate::{
core::revenue_recovery::schedule::StaticLadderProgress, db::StorageInterface,
routes::SessionState, types, workflows::revenue_recovery,
};
+/// What the recovery request workflow needs to process one transaction the merchant reported.
+/// Process tracker data is stored and logged in clear, so the request is kept encrypted with the
+/// merchant's key, and only identifiers are kept in clear, for debugging.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+pub struct RecoveryRequestTrackingData {
+ /// Id of the recovery request, which the id of its process tracker job is built from: one for
+ /// each transaction of an invoice in a profile.
+ pub recovery_request_id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub profile_id: id_type::ProfileId,
+ pub merchant_reference_id: id_type::PaymentReferenceId,
+ pub connector_transaction_id: String,
+ pub connector: common_types::payments::RecoveryConnector,
+ /// When the API accepted the recovery request.
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub received_at: time::PrimitiveDateTime,
+ /// Version of the stored request's format, which a run checks before reading the request.
+ pub request_version: u8,
+ /// The request exactly as the merchant sent it, encrypted with the merchant's key and base64
+ /// encoded.
+ pub encrypted_request: String,
+}
+
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct RevenueRecoveryWorkflowTrackingData {
pub merchant_id: id_type::MerchantId,
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index 4683f02f3e..b037cf4811 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -17,6 +17,8 @@ pub mod tokenized_data;
pub mod revenue_recovery;
+pub mod recovery_request;
+
pub mod process_dispute;
pub mod dispute_list;
diff --git a/crates/router/src/workflows/recovery_request.rs b/crates/router/src/workflows/recovery_request.rs
new file mode 100644
index 0000000000..3fe90a0fad
--- /dev/null
+++ b/crates/router/src/workflows/recovery_request.rs
@@ -0,0 +1,79 @@
+//! The recovery request workflow, which records a transaction the merchant reported on a profile
+//! whose retries it triggers, and decides the next retry of its invoice.
+
+use common_utils::errors::CustomResult;
+#[cfg(feature = "v2")]
+use common_utils::ext_traits::ValueExt;
+#[cfg(feature = "v2")]
+use router_env::logger;
+#[cfg(feature = "v1")]
+use scheduler::consumer;
+use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors};
+
+#[cfg(feature = "v2")]
+use crate::{core::revenue_recovery::external_triggers, types::storage::revenue_recovery as pcr};
+use crate::{routes::SessionState, types::storage};
+
+pub struct RecoveryRequestWorkflow;
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for RecoveryRequestWorkflow {
+ #[cfg(feature = "v1")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ Ok(())
+ }
+
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let tracking_data = match process
+ .tracking_data
+ .clone()
+ .parse_value::<pcr::RecoveryRequestTrackingData>("RecoveryRequestTrackingData")
+ {
+ Ok(tracking_data) => tracking_data,
+ Err(error) => {
+ logger::error!(
+ ?error,
+ process_id = %process.id,
+ "The recovery request's tracking data cannot be read"
+ );
+ return external_triggers::finish_failed_recovery_request(state, &process).await;
+ }
+ };
+ Box::pin(external_triggers::process_recovery_request(
+ state,
+ &process,
+ tracking_data,
+ ))
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ async fn error_handler<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ error: errors::ProcessTrackerError,
+ ) -> CustomResult<(), errors::ProcessTrackerError> {
+ consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
+ }
+
+ /// The workflow returns an error only for a temporary one, so the recovery request runs again.
+ #[cfg(feature = "v2")]
+ async fn error_handler<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ error: errors::ProcessTrackerError,
+ ) -> CustomResult<(), errors::ProcessTrackerError> {
+ external_triggers::retry_recovery_request(state, process, error).await
+ }
+}
diff --git a/crates/router_env/src/metrics.rs b/crates/router_env/src/metrics.rs
index e1db5e4929..0f77aee840 100644
--- a/crates/router_env/src/metrics.rs
+++ b/crates/router_env/src/metrics.rs
@@ -104,6 +104,19 @@ macro_rules! histogram_metric_f64 {
.build()
});
};
+ ($name:ident, $meter:ident, name: $metric_name:literal, description: $description:literal, unit: $unit:literal, boundaries: $boundaries:expr $(,)?) => {
+ #[doc = $description]
+ pub(crate) static $name: ::std::sync::LazyLock<
+ $crate::opentelemetry::metrics::Histogram<f64>,
+ > = ::std::sync::LazyLock::new(|| {
+ $meter
+ .f64_histogram($metric_name)
+ .with_description($description)
+ .with_unit($unit)
+ .with_boundaries($boundaries)
+ .build()
+ });
+ };
}
/// Create a [`Histogram`][Histogram] u64 metric with the specified name and an optional description,