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

fix(refunds): serialize payment-scoped refund reservation (#14923)

Ayush Anand62bd8206285f
diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs
index f583c94192..c7b3d6238d 100644
--- a/crates/router/src/compatibility/stripe/refunds.rs
+++ b/crates/router/src/compatibility/stripe/refunds.rs
@@ -6,7 +6,10 @@ use router_env::{instrument, tracing, Flow, Tag};
use crate::{
compatibility::{stripe::errors, wrap},
- core::{api_locking, refunds},
+ core::{
+ api_locking::{self, GetLockingInput},
+ refunds,
+ },
logger, routes,
services::{api, authentication as auth},
types::api::refunds as refund_types,
@@ -34,6 +37,7 @@ pub async fn refund_create(
let create_refund_req: refund_types::RefundRequest = payload.into();
let flow = Flow::RefundsCreate;
+ let locking_action = create_refund_req.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
@@ -56,7 +60,7 @@ pub async fn refund_create(
allow_connected_scope_operation: false,
allow_platform_self_operation: false,
}),
- api_locking::LockAction::NotApplicable,
+ locking_action,
))
.await
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 5f3d79f69e..e8b0d6fa4a 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1833,66 +1833,60 @@ pub async fn validate_and_create_refund(
.map(|created_by| created_by.to_string()),
};
- let (refund, raw_connector_response) = match db
+ let refund = match db
.insert_refund(
refund_create_req,
platform.get_processor().get_account().storage_scheme,
)
.await
{
- Ok(refund) => {
- let (updated_refund, raw_response) = Box::pin(schedule_refund_execution(
- state,
- refund.clone(),
- refund_type,
- platform,
- payment_attempt,
- payment_intent,
- creds_identifier,
- split_refunds,
- req.all_keys_required,
- payment_method_data,
- ))
- .await?;
-
- // Update the state metadata of the payment intent if the refund is successful
- if updated_refund.refund_status.is_success() {
- tokio::spawn({
- let state = state.clone();
- let processor = platform.get_processor().clone();
- let payment_intent = payment_intent.clone();
- let state_metadata = payment_intent.state_metadata.clone().unwrap_or_default();
-
- async move {
- if let Err(err) = PaymentIntentStateMetadataExt::from(state_metadata)
- .update_intent_state_metadata_for_refund(
- &state,
- &processor,
- payment_intent,
- )
- .await
- {
- logger::error!(
- ?err,
- "Failed to update payment intent state metadata during refund creation"
- );
- }
- }
- .in_current_span()
- });
- }
- (updated_refund, raw_response)
- }
+ Ok(refund) => refund,
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
return Err(err)
- .change_context(errors::ApiErrorResponse::RefundNotFound)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Inserting Refund failed");
}
}
};
+ let (refund, raw_connector_response) = Box::pin(schedule_refund_execution(
+ state,
+ refund,
+ refund_type,
+ platform,
+ payment_attempt,
+ payment_intent,
+ creds_identifier,
+ split_refunds,
+ req.all_keys_required,
+ payment_method_data,
+ ))
+ .await?;
+
+ // Update the state metadata of the payment intent if the refund is successful
+ if refund.refund_status.is_success() {
+ tokio::spawn({
+ let state = state.clone();
+ let processor = platform.get_processor().clone();
+ let payment_intent = payment_intent.clone();
+ let state_metadata = payment_intent.state_metadata.clone().unwrap_or_default();
+
+ async move {
+ if let Err(err) = PaymentIntentStateMetadataExt::from(state_metadata)
+ .update_intent_state_metadata_for_refund(&state, &processor, payment_intent)
+ .await
+ {
+ logger::error!(
+ ?err,
+ "Failed to update payment intent state metadata during refund creation"
+ );
+ }
+ }
+ .in_current_span()
+ });
+ }
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs
index 68b58454bc..d0bbad9c1a 100644
--- a/crates/router/src/core/refunds_v2.rs
+++ b/crates/router/src/core/refunds_v2.rs
@@ -1283,26 +1283,14 @@ pub async fn validate_and_create_refund(
.map(|created_by| created_by.to_string()),
};
- let (refund, raw_connector_response) = match db
+ let refund = match db
.insert_refund(
refund_create_req,
platform.get_processor().get_account().storage_scheme,
)
.await
{
- Ok(refund) => {
- Box::pin(schedule_refund_execution(
- state,
- refund.clone(),
- refund_type,
- platform.get_processor(),
- payment_attempt,
- payment_intent,
- merchant_connector_details,
- req.return_raw_connector_response,
- ))
- .await?
- }
+ Ok(refund) => refund,
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
@@ -1313,6 +1301,17 @@ pub async fn validate_and_create_refund(
}
}
};
+ let (refund, raw_connector_response) = Box::pin(schedule_refund_execution(
+ state,
+ refund,
+ refund_type,
+ platform.get_processor(),
+ payment_attempt,
+ payment_intent,
+ merchant_connector_details,
+ req.return_raw_connector_response,
+ ))
+ .await?;
let unified_translated_message =
match (refund.unified_code.clone(), refund.unified_message.clone()) {
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 18343157a5..f873c5ce0a 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -7,11 +7,30 @@ use crate::core::refunds::*;
#[cfg(feature = "v2")]
use crate::core::refunds_v2::*;
use crate::{
- core::api_locking,
+ core::api_locking::{self, GetLockingInput},
+ routes::lock_utils,
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::refunds,
};
+/// Serializes refund creation against the same payment before balance validation.
+#[cfg(feature = "v1")]
+impl GetLockingInput for refunds::RefundRequest {
+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
+ where
+ F: router_env::types::FlowMetric,
+ lock_utils::ApiIdentifier: From<F>,
+ {
+ api_locking::LockAction::Hold {
+ input: api_locking::LockingInput {
+ unique_locking_key: self.payment_id.get_string_repr().to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::from(flow),
+ override_lock_retries: None,
+ },
+ }
+ }
+}
+
#[cfg(feature = "v2")]
/// A private module to hold internal types to be used in route handlers.
/// This is because we will need to implement certain traits on these types which will have the resource id
@@ -41,6 +60,25 @@ mod internal_payload_types {
})
}
}
+
+ impl<T: serde::Serialize> GetLockingInput for RefundsGenericRequestWithResourceId<T> {
+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
+ where
+ F: router_env::types::FlowMetric,
+ lock_utils::ApiIdentifier: From<F>,
+ {
+ match self.payment_id.as_ref() {
+ Some(payment_id) => api_locking::LockAction::Hold {
+ input: api_locking::LockingInput {
+ unique_locking_key: payment_id.get_string_repr().to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::from(flow),
+ override_lock_retries: None,
+ },
+ },
+ None => api_locking::LockAction::NotApplicable,
+ }
+ }
+ }
}
/// Refunds - Create
@@ -55,11 +93,13 @@ pub async fn refunds_create(
json_payload: web::Json<refunds::RefundRequest>,
) -> HttpResponse {
let flow = Flow::RefundsCreate;
+ let payload = json_payload.into_inner();
+ let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
- json_payload.into_inner(),
+ payload,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
refund_create_core(state, auth.platform, profile_id, req)
@@ -77,7 +117,7 @@ pub async fn refunds_create(
},
req.headers(),
),
- api_locking::LockAction::NotApplicable,
+ locking_action,
))
.await
}
@@ -103,6 +143,8 @@ pub async fn refunds_create(
payload,
};
+ let locking_action = internal_refund_create_payload.get_locking_input(flow.clone());
+
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
@@ -129,7 +171,7 @@ pub async fn refunds_create(
refund_create_core(state, auth.platform, req.payload, global_refund_id.clone())
},
auth_type,
- api_locking::LockAction::NotApplicable,
+ locking_action,
))
.await
}