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(payments): add api locking for payments core (#1898)
Abhishek Marrivagu5d661561322a
diff --git a/Cargo.lock b/Cargo.lockindex 6e5967aede..e0ad241cbe 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4988,36 +4988,36 @@ dependencies = [[[package]]name = "test-case"-version = "3.1.0"+version = "3.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2a1d6e7bde536b0412f20765b76e921028059adfd1b90d8974d33fd3c91b25df"+checksum = "c8f1e820b7f1d95a0cdbf97a5df9de10e1be731983ab943e56703ac1b8e9d425"dependencies = ["test-case-macros",][[package]]name = "test-case-core"-version = "3.1.0"+version = "3.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d10394d5d1e27794f772b6fc854c7e91a2dc26e2cbf807ad523370c2a59c0cee"+checksum = "54c25e2cb8f5fcd7318157634e8838aa6f7e4715c96637f969fabaccd1ef5462"dependencies = ["cfg-if","proc-macro-error","proc-macro2","quote",- "syn 1.0.109",+ "syn 2.0.29",][[package]]name = "test-case-macros"-version = "3.1.0"+version = "3.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eeb9a44b1c6a54c1ba58b152797739dba2a83ca74e18168a68c980eb142f9404"+checksum = "37cfd7bbc88a0104e304229fba519bdc45501a30b760fb72240342f1289ad257"dependencies = ["proc-macro-error","proc-macro2","quote",- "syn 1.0.109",+ "syn 2.0.29","test-case-core",]diff --git a/config/development.toml b/config/development.tomlindex 85bc93822a..0f95dcb657 100644--- a/config/development.toml+++ b/config/development.toml@@ -432,3 +432,7 @@ apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE"apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY"apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE"apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY"++[lock_settings]+redis_lock_expiry_seconds = 180 # 3 * 60 seconds+delay_between_retries_in_milliseconds = 500diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 796a1642ba..6a06b76d0e 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -1512,7 +1512,8 @@ pub struct PhoneDetails {#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]pub struct PaymentsCaptureRequest {/// The unique identifier for the payment- pub payment_id: Option<String>,+ #[serde(skip_deserializing)]+ pub payment_id: String,/// The unique identifier for the merchantpub merchant_id: Option<String>,/// The Amount to be captured/ debited from the user's payment method.diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rsindex 3f3985997f..e76fe7dff5 100644--- a/crates/common_utils/src/ext_traits.rs+++ b/crates/common_utils/src/ext_traits.rs@@ -442,6 +442,12 @@ pub trait ConfigExt {}}+impl ConfigExt for u32 {+ fn is_empty_after_trim(&self) -> bool {+ false+ }+}+impl ConfigExt for String {fn is_empty_after_trim(&self) -> bool {self.trim().is_empty()diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 753f9cc491..39e49f1ff4 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -26,6 +26,7 @@ dummy_connector = ["api_models/dummy_connector"]external_access_dc = ["dummy_connector"]detailed_errors = ["api_models/detailed_errors", "error-stack/serde"]payouts = []+api_locking = [][dependencies]diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rsindex 5e9a189936..cd2ce4835e 100644--- a/crates/router/src/compatibility/stripe/customers.rs+++ b/crates/router/src/compatibility/stripe/customers.rs@@ -1,12 +1,11 @@pub mod types;-use actix_web::{web, HttpRequest, HttpResponse};use error_stack::report;use router_env::{instrument, tracing, Flow};use crate::{compatibility::{stripe::errors, wrap},- core::{customers, payment_methods::cards},+ core::{api_locking, customers, payment_methods::cards},routes,services::{api, authentication as auth},types::api::{customers as customer_types, payment_methods},@@ -49,10 +48,10 @@ pub async fn customer_create(customers::create_customer(state, auth.merchant_account, auth.key_store, req)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]pub async fn customer_retrieve(state: web::Data<routes::AppState>,@@ -84,10 +83,10 @@ pub async fn customer_retrieve(customers::retrieve_customer(state, auth.merchant_account, auth.key_store, req)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]pub async fn customer_update(state: web::Data<routes::AppState>,@@ -128,10 +127,10 @@ pub async fn customer_update(customers::update_customer(state, auth.merchant_account, req, auth.key_store)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]pub async fn customer_delete(state: web::Data<routes::AppState>,@@ -163,10 +162,10 @@ pub async fn customer_delete(customers::delete_customer(state, auth.merchant_account, req, auth.key_store)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]pub async fn list_customer_payment_method_api(state: web::Data<routes::AppState>,@@ -203,6 +202,7 @@ pub async fn list_customer_payment_method_api()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex 888ffb4574..f673d3eb6b 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -232,6 +232,8 @@ pub enum StripeErrorCode {HyperswitchUnprocessableEntity { message: String },#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")]CurrencyNotSupported { message: String },+ #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")]+ LockTimeout,// [#216]: https://github.com/juspay/hyperswitch/issues/216// Implement the remaining stripe error codes@@ -578,6 +580,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => {Self::PaymentMethodUnactivated}+ errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated,}}}@@ -654,6 +657,7 @@ impl actix_web::ResponseError for StripeErrorCode {Self::ExternalConnectorError { status_code, .. } => {StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)}+ Self::LockTimeout => StatusCode::LOCKED,}}diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rsindex 01e5e3857b..e44ce0a1fd 100644--- a/crates/router/src/compatibility/stripe/payment_intents.rs+++ b/crates/router/src/compatibility/stripe/payment_intents.rs@@ -1,5 +1,4 @@pub mod types;-use actix_web::{web, HttpRequest, HttpResponse};use api_models::payments as payment_types;use error_stack::report;@@ -7,7 +6,7 @@ use router_env::{instrument, tracing, Flow};use crate::{compatibility::{stripe::errors, wrap},- core::payments,+ core::{api_locking::GetLockingInput, payments},routes,services::{api, authentication as auth},types::api::{self as api_types},@@ -34,7 +33,7 @@ pub async fn payment_intents_create(};let flow = Flow::PaymentsCreate;-+ let locking_action = create_payment_req.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -63,10 +62,10 @@ pub async fn payment_intents_create()},&auth::ApiKeyAuth,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))]pub async fn payment_intents_retrieve(state: web::Data<routes::AppState>,@@ -93,7 +92,7 @@ pub async fn payment_intents_retrieve(};let flow = Flow::PaymentsRetrieve;-+ let locking_action = payload.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -122,10 +121,10 @@ pub async fn payment_intents_retrieve()},&*auth_type,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))]pub async fn payment_intents_retrieve_with_gateway_creds(state: web::Data<routes::AppState>,@@ -156,7 +155,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds(};let flow = Flow::PaymentsRetrieve;-+ let locking_action = payload.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -185,10 +184,10 @@ pub async fn payment_intents_retrieve_with_gateway_creds()},&*auth_type,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))]pub async fn payment_intents_update(state: web::Data<routes::AppState>,@@ -220,7 +219,7 @@ pub async fn payment_intents_update(};let flow = Flow::PaymentsUpdate;-+ let locking_action = payload.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -249,10 +248,10 @@ pub async fn payment_intents_update()},&*auth_type,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))]pub async fn payment_intents_confirm(state: web::Data<routes::AppState>,@@ -286,7 +285,7 @@ pub async fn payment_intents_confirm(};let flow = Flow::PaymentsConfirm;-+ let locking_action = payload.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -315,10 +314,10 @@ pub async fn payment_intents_confirm()},&*auth_type,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture))]pub async fn payment_intents_capture(state: web::Data<routes::AppState>,@@ -336,13 +335,13 @@ pub async fn payment_intents_capture(}};- let capture_payload = payment_types::PaymentsCaptureRequest {- payment_id: Some(path.into_inner()),+ let payload = payment_types::PaymentsCaptureRequest {+ payment_id: path.into_inner(),..stripe_payload};let flow = Flow::PaymentsCapture;-+ let locking_action = payload.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -357,7 +356,7 @@ pub async fn payment_intents_capture(flow,state.into_inner(),&req,- capture_payload,+ payload,|state, auth, payload| {payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _>(state,@@ -371,10 +370,10 @@ pub async fn payment_intents_capture()},&auth::ApiKeyAuth,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel))]pub async fn payment_intents_cancel(state: web::Data<routes::AppState>,@@ -402,7 +401,7 @@ pub async fn payment_intents_cancel(};let flow = Flow::PaymentsCancel;-+ let locking_action = payload.get_locking_input(flow.clone());Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -431,10 +430,10 @@ pub async fn payment_intents_cancel()},&*auth_type,+ locking_action,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]#[cfg(feature = "olap")]pub async fn payment_intent_list(@@ -446,9 +445,8 @@ pub async fn payment_intent_list(Ok(p) => p,Err(err) => return api::log_and_return_error_response(err),};-+ use crate::core::api_locking;let flow = Flow::PaymentsList;-Box::pin(wrap::compatibility_api_wrap::<_,_,@@ -466,6 +464,7 @@ pub async fn payment_intent_list(payload,|state, auth, req| payments::list_payments(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rsindex 697a7faa8a..dc14744382 100644--- a/crates/router/src/compatibility/stripe/refunds.rs+++ b/crates/router/src/compatibility/stripe/refunds.rs@@ -1,12 +1,11 @@pub mod types;-use actix_web::{web, HttpRequest, HttpResponse};use error_stack::report;use router_env::{instrument, tracing, Flow};use crate::{compatibility::{stripe::errors, wrap},- core::refunds,+ core::{api_locking, refunds},routes,services::{api, authentication as auth},types::api::refunds as refund_types,@@ -50,10 +49,10 @@ pub async fn refund_create(refunds::refund_create_core(state, auth.merchant_account, auth.key_store, req)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]pub async fn refund_retrieve_with_gateway_creds(state: web::Data<routes::AppState>,@@ -96,10 +95,10 @@ pub async fn refund_retrieve_with_gateway_creds()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]pub async fn refund_retrieve(state: web::Data<routes::AppState>,@@ -139,10 +138,10 @@ pub async fn refund_retrieve()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]pub async fn refund_update(state: web::Data<routes::AppState>,@@ -174,6 +173,7 @@ pub async fn refund_update(refunds::refund_update_core(state, auth.merchant_account, &refund_id, req)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rsindex 849bbc6027..4b25a0e54e 100644--- a/crates/router/src/compatibility/stripe/setup_intents.rs+++ b/crates/router/src/compatibility/stripe/setup_intents.rs@@ -1,5 +1,4 @@pub mod types;-use actix_web::{web, HttpRequest, HttpResponse};use api_models::payments as payment_types;use error_stack::report;@@ -10,7 +9,7 @@ use crate::{stripe::{errors, payment_intents::types as stripe_payment_types},wrap,},- core::payments,+ core::{api_locking, payments},routes,services::{api, authentication as auth},types::api as api_types,@@ -67,10 +66,10 @@ pub async fn setup_intents_create()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))]pub async fn setup_intents_retrieve(state: web::Data<routes::AppState>,@@ -126,10 +125,10 @@ pub async fn setup_intents_retrieve()},&*auth_type,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))]pub async fn setup_intents_update(state: web::Data<routes::AppState>,@@ -191,10 +190,10 @@ pub async fn setup_intents_update()},&*auth_type,+ api_locking::LockAction::NotApplicable,)).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))]pub async fn setup_intents_confirm(state: web::Data<routes::AppState>,@@ -257,6 +256,7 @@ pub async fn setup_intents_confirm()},&*auth_type,+ api_locking::LockAction::NotApplicable,)).await}diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rsindex 24218e0b39..281d323cc5 100644--- a/crates/router/src/compatibility/wrap.rs+++ b/crates/router/src/compatibility/wrap.rs@@ -6,7 +6,7 @@ use router_env::{instrument, tracing, Tag};use serde::Serialize;use crate::{- core::errors::{self},+ core::{api_locking, errors},routes::{app::AppStateInfo, metrics},services::{self, api, authentication as auth, logger},};@@ -19,6 +19,7 @@ pub async fn compatibility_api_wrap<'a, 'b, A, U, T, Q, F, Fut, S, E, E2>(payload: T,func: F,api_authentication: &dyn auth::AuthenticateAndFetch<U, A>,+ lock_action: api_locking::LockAction,) -> HttpResponsewhereF: Fn(A, U, T) -> Fut,@@ -49,6 +50,7 @@ wherepayload,func,api_authentication,+ lock_action,),&flow,)diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 675a7ccec0..b5e522cf84 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -98,6 +98,7 @@ pub struct Settings {pub applepay_decrypt_keys: ApplePayDecryptConifg,pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,pub applepay_merchant_configs: ApplepayMerchantConfigs,+ pub lock_settings: LockSettings,pub temp_locker_disable_config: TempLockerDisableConfig,}@@ -746,6 +747,7 @@ impl Settings {.map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?;#[cfg(feature = "s3")]self.file_upload_config.validate()?;+ self.lock_settings.validate()?;Ok(())}}@@ -773,3 +775,32 @@ mod payment_method_deserialization_test {pub struct Payouts {pub payout_eligibility: bool,}++#[derive(Debug, Clone, Default)]+pub struct LockSettings {+ pub redis_lock_expiry_seconds: u32,+ pub delay_between_retries_in_milliseconds: u32,+ pub lock_retries: u32,+}++impl<'de> Deserialize<'de> for LockSettings {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Inner {+ redis_lock_expiry_seconds: u32,+ delay_between_retries_in_milliseconds: u32,+ }++ let Inner {+ redis_lock_expiry_seconds,+ delay_between_retries_in_milliseconds,+ } = Inner::deserialize(deserializer)?;+ let redis_lock_expiry_seconds = redis_lock_expiry_seconds * 1000;+ Ok(Self {+ redis_lock_expiry_seconds,+ delay_between_retries_in_milliseconds,+ lock_retries: redis_lock_expiry_seconds / delay_between_retries_in_milliseconds,+ })+ }+}diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex 702852a1fc..569262d0d2 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -165,3 +165,31 @@ impl super::settings::ApiKeys {})}}++impl super::settings::LockSettings {+ pub fn validate(&self) -> Result<(), ApplicationError> {+ use common_utils::fp_utils::when;++ when(self.redis_lock_expiry_seconds.is_default_or_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "redis_lock_expiry_seconds must not be empty or 0".into(),+ ))+ })?;++ when(+ self.delay_between_retries_in_milliseconds+ .is_default_or_empty(),+ || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "delay_between_retries_in_milliseconds must not be empty or 0".into(),+ ))+ },+ )?;++ when(self.lock_retries.is_default_or_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "lock_retries must not be empty or 0".into(),+ ))+ })+ }+}diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 545553cae4..2e090a6436 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -1,5 +1,6 @@pub mod admin;pub mod api_keys;+pub mod api_locking;pub mod cache;pub mod cards_info;pub mod configs;diff --git a/crates/router/src/core/api_locking.rs b/crates/router/src/core/api_locking.rsnew file mode 100644index 0000000000..b5c3f8ae53--- /dev/null+++ b/crates/router/src/core/api_locking.rs@@ -0,0 +1,168 @@+use std::fmt::Debug;++use actix_web::rt::time as actix_time;+use error_stack::{IntoReport, ResultExt};+use redis_interface as redis;+use router_env::{instrument, logger, tracing};++use super::errors::{self, RouterResult};+use crate::routes::{app::AppStateInfo, lock_utils};++pub const API_LOCK_PREFIX: &str = "API_LOCK";++#[derive(Clone, Debug, Eq, PartialEq)]+pub enum LockStatus {+ // status when the lock is acquired by the caller+ Acquired, // [#2129] pick up request_id from AppState and populate here+ // status when the lock is acquired by some other caller+ Busy,+}++#[derive(Clone, Debug)]+pub enum LockAction {+ // Sleep until the lock is acquired+ Hold { input: LockingInput },+ // Queue it but return response as 2xx, could be used for webhooks+ QueueWithOk,+ // Return Error+ Drop,+ // Locking Not applicable+ NotApplicable,+}++#[derive(Clone, Debug)]+pub struct LockingInput {+ pub unique_locking_key: String,+ pub api_identifier: lock_utils::ApiIdentifier,+ pub override_lock_retries: Option<u32>,+}++impl LockingInput {+ fn get_redis_locking_key(&self, merchant_id: String) -> String {+ format!(+ "{}_{}_{}_{}",+ API_LOCK_PREFIX, merchant_id, self.api_identifier, self.unique_locking_key+ )+ }+}++impl LockAction {+ #[instrument(skip_all)]+ pub async fn perform_locking_action<A>(self, state: &A, merchant_id: String) -> RouterResult<()>+ where+ A: AppStateInfo,+ {+ match self {+ Self::Hold { input } => {+ let redis_conn = state+ .store()+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let redis_locking_key = input.get_redis_locking_key(merchant_id);+ let delay_between_retries_in_milliseconds = state+ .conf()+ .lock_settings+ .delay_between_retries_in_milliseconds;+ let redis_lock_expiry_seconds =+ state.conf().lock_settings.redis_lock_expiry_seconds;+ let lock_retries = input+ .override_lock_retries+ .unwrap_or(state.conf().lock_settings.lock_retries);+ for _retry in 0..lock_retries {+ let redis_lock_result = redis_conn+ .set_key_if_not_exists_with_expiry(+ redis_locking_key.as_str(),+ state.get_request_id(),+ Some(i64::from(redis_lock_expiry_seconds)),+ )+ .await;++ match redis_lock_result {+ Ok(redis::SetnxReply::KeySet) => {+ logger::info!("Lock acquired for locking input {:?}", input);+ tracing::Span::current()+ .record("redis_lock_acquired", redis_locking_key);+ return Ok(());+ }+ Ok(redis::SetnxReply::KeyNotSet) => {+ logger::info!(+ "Lock busy by other request when tried for locking input {:?}",+ input+ );+ actix_time::sleep(tokio::time::Duration::from_millis(u64::from(+ delay_between_retries_in_milliseconds,+ )))+ .await;+ }+ Err(err) => {+ return Err(err)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ }+ }+ }++ Err(errors::ApiErrorResponse::ResourceBusy).into_report()+ }+ Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),+ }+ }++ #[instrument(skip_all)]+ pub async fn free_lock_action<A>(self, state: &A, merchant_id: String) -> RouterResult<()>+ where+ A: AppStateInfo,+ {+ match self {+ Self::Hold { input } => {+ let redis_conn = state+ .store()+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let redis_locking_key = input.get_redis_locking_key(merchant_id);++ match redis_conn+ .get_key::<Option<String>>(&redis_locking_key)+ .await+ {+ Ok(val) => {+ if val == state.get_request_id() {+ match redis_conn.delete_key(redis_locking_key.as_str()).await {+ Ok(redis::types::DelReply::KeyDeleted) => {+ logger::info!("Lock freed for locking input {:?}", input);+ tracing::Span::current()+ .record("redis_lock_released", redis_locking_key);+ Ok(())+ }+ Ok(redis::types::DelReply::KeyNotDeleted) => Err(+ errors::ApiErrorResponse::InternalServerError,+ )+ .into_report()+ .attach_printable(+ "Status release lock called but key is not found in redis",+ ),+ Err(error) => Err(error)+ .change_context(errors::ApiErrorResponse::InternalServerError),+ }+ } else {+ Err(errors::ApiErrorResponse::InternalServerError)+ .into_report().attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock")+ }+ }+ Err(error) => {+ Err(error).change_context(errors::ApiErrorResponse::InternalServerError)+ }+ }+ }+ Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),+ }+ }+}++pub trait GetLockingInput {+ fn get_locking_input<F>(&self, flow: F) -> LockAction+ where+ F: router_env::types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>;+}diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rsindex f38891931f..6224f5e481 100644--- a/crates/router/src/core/errors/api_error_response.rs+++ b/crates/router/src/core/errors/api_error_response.rs@@ -15,6 +15,7 @@ pub enum ErrorType {DuplicateRequest,ValidationError,ConnectorError,+ LockTimeout,}#[allow(dead_code)]@@ -124,6 +125,8 @@ pub enum ApiErrorResponse {#[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]InternalServerError,+ #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]+ ResourceBusy,#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]DuplicateRefundRequest,#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rsindex 3c9572efa1..1c89985217 100644--- a/crates/router/src/core/errors/transformers.rs+++ b/crates/router/src/core/errors/transformers.rs@@ -257,6 +257,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon}Self::WebhookUnprocessableEntity => {AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))+ },+ Self::ResourceBusy => {+ AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))}}}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 84c359c687..170a780e70 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -92,6 +92,7 @@ where.validate_request(&req, &merchant_account)?;tracing::Span::current().record("payment_id", &format!("{}", validate_result.payment_id));+let (operation, mut payment_data, customer_details) = operation.to_get_tracker()?.get_trackers(diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rsindex e270a8df49..c3b915f9d3 100644--- a/crates/router/src/core/payments/operations/payment_capture.rs+++ b/crates/router/src/core/payments/operations/payment_capture.rs@@ -284,16 +284,11 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for PaymenBoxedOperation<'b, F, api::PaymentsCaptureRequest>,operations::ValidateResult<'a>,)> {- let payment_id = request- .payment_id- .as_ref()- .get_required_value("payment_id")?;-Ok((Box::new(self),operations::ValidateResult {merchant_id: &merchant_account.merchant_id,- payment_id: api::PaymentIdType::PaymentIntentId(payment_id.to_owned()),+ payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),mandate_type: None,storage_scheme: merchant_account.storage_scheme,requeue: false,diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rsindex 9a75a295f5..ed7ba920b7 100644--- a/crates/router/src/core/webhooks.rs+++ b/crates/router/src/core/webhooks.rs@@ -15,11 +15,13 @@ use crate::compatibility::stripe::webhooks as stripe_webhooks;use crate::{consts,core::{+ api_locking,errors::{self, ConnectorErrorExt, CustomResult, RouterResponse},payments, refunds,},+ db::StorageInterface,logger,- routes::{metrics::request::add_attributes, AppState},+ routes::{lock_utils, metrics::request::add_attributes, AppState},services,types::{self as router_types, api, domain,@@ -32,7 +34,6 @@ use crate::{const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5;const MERCHANT_ID: &str = "merchant_id";-#[instrument(skip_all)]pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>(state: AppState,merchant_account: domain::MerchantAccount,@@ -47,6 +48,27 @@ pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>(};let payments_response = match webhook_details.object_reference_id {api_models::webhooks::ObjectReferenceId::PaymentId(id) => {+ let payment_id = get_payment_id(+ state.store.as_ref(),+ &id,+ merchant_account.merchant_id.as_str(),+ merchant_account.storage_scheme,+ )+ .await?;++ let lock_action = api_locking::LockAction::Hold {+ input: super::api_locking::LockingInput {+ unique_locking_key: payment_id,+ api_identifier: lock_utils::ApiIdentifier::Payments,+ override_lock_retries: None,+ },+ };++ lock_action+ .clone()+ .perform_locking_action(&state, merchant_account.merchant_id.to_string())+ .await?;+let response = payments::payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(state.clone(),merchant_account.clone(),@@ -69,6 +91,10 @@ pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>().await;+ lock_action+ .free_lock_action(&state, merchant_account.merchant_id.to_owned())+ .await?;+match response {Ok(value) => value,Err(err)@@ -957,6 +983,44 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(Ok(response)}+#[inline]+pub async fn get_payment_id(+ db: &dyn StorageInterface,+ payment_id: &api::PaymentIdType,+ merchant_id: &str,+ storage_scheme: enums::MerchantStorageScheme,+) -> errors::RouterResult<String> {+ let pay_id = || async {+ match payment_id {+ api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_string()),+ api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db+ .find_payment_attempt_by_merchant_id_connector_txn_id(+ merchant_id,+ id,+ storage_scheme,+ )+ .await+ .map(|p| p.payment_id),+ api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db+ .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)+ .await+ .map(|p| p.payment_id),+ api_models::payments::PaymentIdType::PreprocessingId(ref id) => db+ .find_payment_attempt_by_preprocessing_id_merchant_id(+ id,+ merchant_id,+ storage_scheme,+ )+ .await+ .map(|p| p.payment_id),+ }+ };++ pay_id()+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+}+async fn fetch_mca_and_connector(state: AppState,merchant_account: &domain::MerchantAccount,diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rsindex dacb9d7b37..f3e85ba5d2 100644--- a/crates/router/src/db/configs.rs+++ b/crates/router/src/db/configs.rs@@ -105,13 +105,14 @@ impl ConfigInterface for Store {&self,key: &str,) -> CustomResult<storage::Config, errors::StorageError> {- cache::get_or_populate_in_memory(- self,- key,- || self.find_config_by_key_from_db(key),- &CONFIG_CACHE,- )- .await+ let find_config_by_key_from_db = || async {+ let conn = connection::pg_connection_write(self).await?;+ storage::Config::find_by_key(&conn, key)+ .await+ .map_err(Into::into)+ .into_report()+ };+ cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await}async fn find_config_by_key_unwrap_or(diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex cf88f0ef07..20357040ce 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -11,6 +11,7 @@ pub mod dummy_connector;pub mod ephemeral_key;pub mod files;pub mod health;+pub mod lock_utils;pub mod mandates;pub mod metrics;pub mod payment_methods;diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rsindex f36094f2d4..f0a0dc4031 100644--- a/crates/router/src/routes/admin.rs+++ b/crates/router/src/routes/admin.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::admin::*,+ core::{admin::*, api_locking},services::{api, authentication as auth},types::api::admin,};@@ -37,10 +37,10 @@ pub async fn merchant_account_create(json_payload.into_inner(),|state, _, req| create_merchant_account(state, req),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Account - Retrieve////// Retrieve a merchant account details.@@ -73,10 +73,10 @@ pub async fn retrieve_merchant_account(payload,|state, _, req| get_merchant_account(state, req),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Account - Update////// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc@@ -109,10 +109,10 @@ pub async fn update_merchant_account(json_payload.into_inner(),|state, _, req| merchant_account_update(state, &merchant_id, req),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Account - Delete////// To delete a merchant account@@ -146,10 +146,10 @@ pub async fn delete_merchant_account(payload,|state, _, req| merchant_account_delete(state, req.merchant_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// PaymentsConnectors - Create////// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."@@ -181,10 +181,10 @@ pub async fn payment_connector_create(json_payload.into_inner(),|state, _, req| create_payment_connector(state, req, &merchant_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Connector - Retrieve////// Retrieve Merchant Connector Details@@ -227,10 +227,10 @@ pub async fn payment_connector_retrieve(retrieve_payment_connector(state, req.merchant_id, req.merchant_connector_id)},&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Connector - List////// List Merchant Connector Details for the merchant@@ -265,10 +265,10 @@ pub async fn payment_connector_list(merchant_id,|state, _, merchant_id| list_payment_connectors(state, merchant_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Connector - Update////// To update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.@@ -306,10 +306,10 @@ pub async fn payment_connector_update(json_payload.into_inner(),|state, _, req| update_payment_connector(state, &merchant_id, &merchant_connector_id, req),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Connector - Delete////// Delete or Detach a Merchant Connector from Merchant Account@@ -350,10 +350,10 @@ pub async fn payment_connector_delete(payload,|state, _, req| delete_payment_connector(state, req.merchant_id, req.merchant_connector_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Account - Toggle KV////// Toggle KV mode for the Merchant Account@@ -375,10 +375,10 @@ pub async fn merchant_account_toggle_kv((merchant_id, payload),|state, _, (merchant_id, payload)| kv_for_merchant(state, merchant_id, payload.kv_enabled),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileCreate))]pub async fn business_profile_create(state: web::Data<AppState>,@@ -397,10 +397,10 @@ pub async fn business_profile_create(payload,|state, _, req| create_business_profile(state, req, &merchant_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileRetrieve))]pub async fn business_profile_retrieve(state: web::Data<AppState>,@@ -417,10 +417,10 @@ pub async fn business_profile_retrieve(profile_id,|state, _, profile_id| retrieve_business_profile(state, profile_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileUpdate))]pub async fn business_profile_update(state: web::Data<AppState>,@@ -438,10 +438,10 @@ pub async fn business_profile_update(json_payload.into_inner(),|state, _, req| update_business_profile(state, &profile_id, &merchant_id, req),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileDelete))]pub async fn business_profile_delete(state: web::Data<AppState>,@@ -458,10 +458,10 @@ pub async fn business_profile_delete(profile_id,|state, _, profile_id| delete_business_profile(state, profile_id, &merchant_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileList))]pub async fn business_profiles_list(state: web::Data<AppState>,@@ -478,10 +478,10 @@ pub async fn business_profiles_list(merchant_id,|state, _, merchant_id| list_business_profile(state, merchant_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Merchant Account - KV Status////// Toggle KV mode for the Merchant Account@@ -501,6 +501,7 @@ pub async fn merchant_account_kv_status(merchant_id,|state, _, req| check_merchant_account_kv_status(state, req),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rsindex 28f5e92870..6057b4c5db 100644--- a/crates/router/src/routes/api_keys.rs+++ b/crates/router/src/routes/api_keys.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::api_keys,+ core::{api_keys, api_locking},services::{api, authentication as auth},types::api as api_types,};@@ -54,10 +54,10 @@ pub async fn api_key_create(.await},&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// API Key - Retrieve////// Retrieve information about the specified API Key.@@ -92,10 +92,10 @@ pub async fn api_key_retrieve((&merchant_id, &key_id),|state, _, (merchant_id, key_id)| api_keys::retrieve_api_key(state, merchant_id, key_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// API Key - Update////// Update information for the specified API Key.@@ -135,10 +135,10 @@ pub async fn api_key_update(api_keys::update_api_key(state, merchant_id, key_id, payload)},&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// API Key - Revoke////// Revoke the specified API Key. Once revoked, the API Key can no longer be used for@@ -174,10 +174,10 @@ pub async fn api_key_revoke((&merchant_id, &key_id),|state, _, (merchant_id, key_id)| api_keys::revoke_api_key(state, merchant_id, key_id),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-/// API Key - List////// List all API Keys associated with your merchant account.@@ -218,6 +218,7 @@ pub async fn api_key_list(api_keys::list_api_keys(state, merchant_id, limit, offset).await},&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 045c548009..971459dc86 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -55,6 +55,7 @@ pub trait AppStateInfo {fn add_request_id(&mut self, request_id: Option<String>);fn add_merchant_id(&mut self, merchant_id: Option<String>);fn add_flow_name(&mut self, flow_name: String);+ fn get_request_id(&self) -> Option<String>;}impl AppStateInfo for AppState {@@ -77,6 +78,9 @@ impl AppStateInfo for AppState {fn add_flow_name(&mut self, flow_name: String) {self.api_client.add_flow_name(flow_name);}+ fn get_request_id(&self) -> Option<String> {+ self.api_client.get_request_id()+ }}impl AsRef<Self> for AppState {diff --git a/crates/router/src/routes/cache.rs b/crates/router/src/routes/cache.rsindex 419f8a95f2..520d6ab7db 100644--- a/crates/router/src/routes/cache.rs+++ b/crates/router/src/routes/cache.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::AppState;use crate::{- core::cache,+ core::{api_locking, cache},services::{api, authentication as auth},};@@ -24,6 +24,7 @@ pub async fn invalidate(&key,|state, _, key| cache::invalidate(state, key),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/cards_info.rs b/crates/router/src/routes/cards_info.rsindex ff2acacf9b..79a2061ac4 100644--- a/crates/router/src/routes/cards_info.rs+++ b/crates/router/src/routes/cards_info.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::cards_info,+ core::{api_locking, cards_info},services::{api, authentication as auth},};@@ -48,6 +48,7 @@ pub async fn card_iin_info(payload,|state, auth, req| cards_info::retrieve_card_info(state, auth.merchant_account, req),&*auth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rsindex e48e877018..45eb45a83b 100644--- a/crates/router/src/routes/configs.rs+++ b/crates/router/src/routes/configs.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::configs,+ core::{api_locking, configs},services::{api, authentication as auth},types::api as api_types,};@@ -24,10 +24,10 @@ pub async fn config_key_create(payload,|state, _, data| configs::set_config(state, data),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyFetch))]pub async fn config_key_retrieve(state: web::Data<AppState>,@@ -44,10 +44,10 @@ pub async fn config_key_retrieve(&key,|state, _, key| configs::read_config(state, key),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyUpdate))]pub async fn config_key_update(state: web::Data<AppState>,@@ -67,6 +67,7 @@ pub async fn config_key_update(&payload,|state, _, payload| configs::update_config(state, payload),&auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rsindex 1ad822efcd..de5fdb4d63 100644--- a/crates/router/src/routes/customers.rs+++ b/crates/router/src/routes/customers.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::customers::*,+ core::{api_locking, customers::*},services::{api, authentication as auth},types::api::customers,};@@ -37,10 +37,10 @@ pub async fn customers_create(json_payload.into_inner(),|state, auth, req| create_customer(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Retrieve Customer////// Retrieve a customer's details.@@ -81,10 +81,10 @@ pub async fn customers_retrieve(payload,|state, auth, req| retrieve_customer(state, auth.merchant_account, auth.key_store, req),&*auth,+ api_locking::LockAction::NotApplicable,).await}-/// Update Customer////// Updates the customer's details in a customer object.@@ -118,10 +118,10 @@ pub async fn customers_update(json_payload.into_inner(),|state, auth, req| update_customer(state, auth.merchant_account, req, auth.key_store),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Delete Customer////// Delete a customer record.@@ -155,10 +155,10 @@ pub async fn customers_delete(payload,|state, auth, req| delete_customer(state, auth.merchant_account, req, auth.key_store),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))]pub async fn get_customer_mandates(state: web::Data<AppState>,@@ -179,6 +179,7 @@ pub async fn get_customer_mandates(crate::core::mandate::get_customer_mandates(state, auth.merchant_account, req)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rsindex 61574a5528..d570a53196 100644--- a/crates/router/src/routes/disputes.rs+++ b/crates/router/src/routes/disputes.rs@@ -2,6 +2,8 @@ use actix_multipart::Multipart;use actix_web::{web, HttpRequest, HttpResponse};use api_models::disputes as dispute_models;use router_env::{instrument, tracing, Flow};++use crate::core::api_locking;pub mod utils;use super::app::AppState;@@ -43,10 +45,10 @@ pub async fn retrieve_dispute(dispute_id,|state, auth, req| disputes::retrieve_dispute(state, auth.merchant_account, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Disputes - List Disputes#[utoipa::path(get,@@ -86,10 +88,10 @@ pub async fn retrieve_disputes_list(payload,|state, auth, req| disputes::retrieve_disputes_list(state, auth.merchant_account, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Disputes - Accept Dispute#[utoipa::path(get,@@ -124,10 +126,10 @@ pub async fn accept_dispute(disputes::accept_dispute(state, auth.merchant_account, auth.key_store, req)},auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Disputes - Submit Dispute Evidence#[utoipa::path(post,@@ -157,10 +159,10 @@ pub async fn submit_dispute_evidence(disputes::submit_evidence(state, auth.merchant_account, auth.key_store, req)},auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Disputes - Attach Evidence to Dispute////// To attach an evidence file to dispute@@ -198,10 +200,10 @@ pub async fn attach_dispute_evidence(disputes::attach_evidence(state, auth.merchant_account, auth.key_store, req)},auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Diputes - Retrieve Dispute#[utoipa::path(get,@@ -234,6 +236,7 @@ pub async fn retrieve_dispute_evidence(dispute_id,|state, auth, req| disputes::retrieve_dispute_evidence(state, auth.merchant_account, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rsindex f64b7ceb77..52a7f7f77c 100644--- a/crates/router/src/routes/dummy_connector.rs+++ b/crates/router/src/routes/dummy_connector.rs@@ -2,7 +2,10 @@ use actix_web::web;use router_env::{instrument, tracing};use super::app;-use crate::services::{api, authentication as auth};+use crate::{+ core::api_locking,+ services::{api, authentication as auth},+};mod consts;mod core;@@ -26,10 +29,10 @@ pub async fn dummy_connector_authorize_payment(payload,|state, _, req| core::payment_authorize(state, req),&auth::NoAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]pub async fn dummy_connector_complete_payment(state: web::Data<app::AppState>,@@ -50,10 +53,10 @@ pub async fn dummy_connector_complete_payment(payload,|state, _, req| core::payment_complete(state, req),&auth::NoAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]pub async fn dummy_connector_payment(state: web::Data<app::AppState>,@@ -69,10 +72,10 @@ pub async fn dummy_connector_payment(payload,|state, _, req| core::payment(state, req),&auth::NoAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))]pub async fn dummy_connector_payment_data(state: web::Data<app::AppState>,@@ -89,10 +92,10 @@ pub async fn dummy_connector_payment_data(payload,|state, _, req| core::payment_data(state, req),&auth::NoAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundCreate))]pub async fn dummy_connector_refund(state: web::Data<app::AppState>,@@ -110,10 +113,10 @@ pub async fn dummy_connector_refund(payload,|state, _, req| core::refund_payment(state, req),&auth::NoAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundRetrieve))]pub async fn dummy_connector_refund_data(state: web::Data<app::AppState>,@@ -130,6 +133,7 @@ pub async fn dummy_connector_refund_data(payload,|state, _, req| core::refund_data(state, req),&auth::NoAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rsindex e0b407c5ba..a9e70c1b33 100644--- a/crates/router/src/routes/ephemeral_key.rs+++ b/crates/router/src/routes/ephemeral_key.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::AppState;use crate::{- core::payments::helpers,+ core::{api_locking, payments::helpers},services::{api, authentication as auth},types::api::customers,};@@ -25,10 +25,10 @@ pub async fn ephemeral_key_create(helpers::make_ephemeral_key(state, req.customer_id, auth.merchant_account.merchant_id)},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]pub async fn ephemeral_key_delete(state: web::Data<AppState>,@@ -44,6 +44,7 @@ pub async fn ephemeral_key_delete(payload,|state, _, req| helpers::delete_ephemeral_key(state, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rsindex cfb3aba6bf..4a327ba080 100644--- a/crates/router/src/routes/files.rs+++ b/crates/router/src/routes/files.rs@@ -1,6 +1,8 @@use actix_multipart::Multipart;use actix_web::{web, HttpRequest, HttpResponse};use router_env::{instrument, tracing, Flow};++use crate::core::api_locking;pub mod transformers;use super::app::AppState;@@ -44,10 +46,10 @@ pub async fn files_create(create_file_request,|state, auth, req| files_create_core(state, auth.merchant_account, auth.key_store, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Files - Delete////// To delete a file@@ -82,10 +84,10 @@ pub async fn files_delete(file_id,|state, auth, req| files_delete_core(state, auth.merchant_account, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}-/// Files - Retrieve////// To retrieve a file@@ -120,6 +122,7 @@ pub async fn files_retrieve(file_id,|state, auth, req| files_retrieve_core(state, auth.merchant_account, auth.key_store, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsnew file mode 100644index 0000000000..80763ab434--- /dev/null+++ b/crates/router/src/routes/lock_utils.rs@@ -0,0 +1,117 @@+use router_env::Flow;++#[derive(Clone, Debug, strum::Display)]+#[strum(serialize_all = "snake_case")]+pub enum ApiIdentifier {+ Payments,+ Refunds,+ Webhooks,+ MerchantAccount,+ MerchantConnector,+ Configs,+ Customers,+ Ephemeral,+ Mandates,+ PaymentMethods,+ Payouts,+ Disputes,+ CardsInfo,+ Files,+ Cache,+ Business,+ Verification,+ ApiKeys,+}++impl From<Flow> for ApiIdentifier {+ fn from(flow: Flow) -> Self {+ match flow {+ Flow::MerchantsAccountCreate+ | Flow::MerchantsAccountRetrieve+ | Flow::MerchantsAccountUpdate+ | Flow::MerchantsAccountDelete => Self::MerchantAccount,++ Flow::MerchantConnectorsCreate+ | Flow::MerchantConnectorsRetrieve+ | Flow::MerchantConnectorsUpdate+ | Flow::MerchantConnectorsDelete+ | Flow::MerchantConnectorsList => Self::MerchantConnector,++ Flow::ConfigKeyCreate+ | Flow::ConfigKeyFetch+ | Flow::ConfigKeyUpdate+ | Flow::CreateConfigKey => Self::Configs,++ Flow::CustomersCreate+ | Flow::CustomersRetrieve+ | Flow::CustomersUpdate+ | Flow::CustomersDelete+ | Flow::CustomersGetMandates => Self::Customers,++ Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,++ Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates,++ Flow::PaymentMethodsCreate+ | Flow::PaymentMethodsList+ | Flow::CustomerPaymentMethodsList+ | Flow::PaymentMethodsRetrieve+ | Flow::PaymentMethodsUpdate+ | Flow::PaymentMethodsDelete+ | Flow::ValidatePaymentMethod => Self::PaymentMethods,++ Flow::PaymentsCreate+ | Flow::PaymentsRetrieve+ | Flow::PaymentsUpdate+ | Flow::PaymentsConfirm+ | Flow::PaymentsCapture+ | Flow::PaymentsCancel+ | Flow::PaymentsApprove+ | Flow::PaymentsReject+ | Flow::PaymentsSessionToken+ | Flow::PaymentsStart+ | Flow::PaymentsList+ | Flow::PaymentsRedirect => Self::Payments,++ Flow::PayoutsCreate+ | Flow::PayoutsRetrieve+ | Flow::PayoutsUpdate+ | Flow::PayoutsCancel+ | Flow::PayoutsFulfill+ | Flow::PayoutsAccounts => Self::Payouts,++ Flow::RefundsCreate+ | Flow::RefundsRetrieve+ | Flow::RefundsUpdate+ | Flow::RefundsList => Self::Refunds,++ Flow::IncomingWebhookReceive => Self::Webhooks,++ Flow::ApiKeyCreate+ | Flow::ApiKeyRetrieve+ | Flow::ApiKeyUpdate+ | Flow::ApiKeyRevoke+ | Flow::ApiKeyList => Self::ApiKeys,++ Flow::DisputesRetrieve+ | Flow::DisputesList+ | Flow::DisputesEvidenceSubmit+ | Flow::AttachDisputeEvidence+ | Flow::RetrieveDisputeEvidence => Self::Disputes,++ Flow::CardsInfo => Self::CardsInfo,++ Flow::CreateFile | Flow::DeleteFile | Flow::RetrieveFile => Self::Files,++ Flow::CacheInvalidate => Self::Cache,++ Flow::BusinessProfileCreate+ | Flow::BusinessProfileUpdate+ | Flow::BusinessProfileRetrieve+ | Flow::BusinessProfileDelete+ | Flow::BusinessProfileList => Self::Business,++ Flow::Verification => Self::Verification,+ }+ }+}diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rsindex d9f32be8cc..0213d48ddc 100644--- a/crates/router/src/routes/mandates.rs+++ b/crates/router/src/routes/mandates.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::mandate,+ core::{api_locking, mandate},services::{api, authentication as auth},types::api::mandates,};@@ -43,10 +43,10 @@ pub async fn get_mandate(mandate_id,|state, auth, req| mandate::get_mandate(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Mandates - Revoke Mandate////// Revoke a mandate@@ -82,10 +82,10 @@ pub async fn revoke_mandate(mandate_id,|state, auth, req| mandate::revoke_mandate(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Mandates - List Mandates#[utoipa::path(get,@@ -123,6 +123,7 @@ pub async fn retrieve_mandates_list(payload,|state, auth, req| mandate::retrieve_mandates_list(state, auth.merchant_account, req),auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 5b7a9cb842..faaf757fd7 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -7,7 +7,7 @@ use time::PrimitiveDateTime;use super::app::AppState;use crate::{- core::{errors, payment_methods::cards},+ core::{api_locking, errors, payment_methods::cards},services::{api, authentication as auth},types::api::payment_methods::{self, PaymentMethodId},};@@ -43,10 +43,10 @@ pub async fn create_payment_method_api(cards::add_payment_method(state, req, &auth.merchant_account, &auth.key_store).await},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// List payment methods for a Merchant////// To filter and list the applicable payment methods for a particular Merchant ID@@ -93,10 +93,10 @@ pub async fn list_payment_method_api(cards::list_payment_methods(state, auth.merchant_account, auth.key_store, req)},&*auth,+ api_locking::LockAction::NotApplicable,).await}-/// List payment methods for a Customer////// To filter and list the applicable payment methods for a particular Customer ID@@ -150,10 +150,10 @@ pub async fn list_customer_payment_method_api()},&*auth,+ api_locking::LockAction::NotApplicable,).await}-/// List payment methods for a Customer////// To filter and list the applicable payment methods for a particular Customer ID@@ -206,10 +206,10 @@ pub async fn list_customer_payment_method_api_client()},&*auth,+ api_locking::LockAction::NotApplicable,).await}-/// Payment Method - Retrieve////// To retrieve a payment method@@ -246,10 +246,10 @@ pub async fn payment_method_retrieve_api(payload,|state, _auth, pm| cards::retrieve_payment_method(state, pm),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Payment Method - Update////// To update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments@@ -293,10 +293,10 @@ pub async fn payment_method_update_api()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Payment Method - Delete////// Delete payment method@@ -331,10 +331,10 @@ pub async fn payment_method_delete_api(pm,|state, auth, req| cards::delete_payment_method(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-#[cfg(test)]mod tests {#![allow(clippy::unwrap_used)]diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 2e73a20554..bd58d55191 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -1,9 +1,10 @@+use crate::core::api_locking::{self, GetLockingInput};pub mod helpers;use actix_web::{web, Responder};use api_models::payments::HeaderPayload;use error_stack::report;-use router_env::{instrument, tracing, Flow};+use router_env::{instrument, tracing, types, Flow};use crate::{self as app,@@ -17,6 +18,7 @@ use crate::{PAYMENTS_CREATE_WITH_MANUAL_CAPTURE, PAYMENTS_CREATE_WITH_NOON_ORDER_CATETORY,PAYMENTS_CREATE_WITH_ORDER_DETAILS,},+ routes::lock_utils,services::{api, authentication as auth},types::{api::{self as api_types, enums as api_enums, payments as payment_types},@@ -96,6 +98,8 @@ pub async fn payments_create(return http_not_implemented();};+ let locking_action = payload.get_locking_input(flow.clone());+api::server_wrap(flow,state,@@ -113,10 +117,10 @@ pub async fn payments_create()},&auth::ApiKeyAuth,+ locking_action,).await}-// /// Payments - Redirect// ///// /// For a payment which involves the redirection flow. This redirects the user to the authentication page@@ -148,7 +152,11 @@ pub async fn payments_start(merchant_id: merchant_id.clone(),attempt_id: attempt_id.clone(),};- api::server_wrap(flow,++ let locking_action = payload.get_locking_input(flow.clone());++ api::server_wrap(+ flow,state,&req,payload,@@ -165,10 +173,10 @@ pub async fn payments_start()},&auth::MerchantIdAuth(merchant_id),+ locking_action,).await}-/// Payments - Retrieve////// To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment@@ -211,6 +219,8 @@ pub async fn payments_retrieve(Err(err) => return api::log_and_return_error_response(report!(err)),};+ let locking_action = payload.get_locking_input(flow.clone());+api::server_wrap(flow,state,@@ -229,10 +239,10 @@ pub async fn payments_retrieve()},&*auth_type,+ locking_action,).await}-/// Payments - Retrieve with gateway credentials////// To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment@@ -269,6 +279,9 @@ pub async fn payments_retrieve_with_gateway_creds(..Default::default()};let flow = Flow::PaymentsRetrieve;++ let locking_action = payload.get_locking_input(flow.clone());+api::server_wrap(flow,state,@@ -287,10 +300,10 @@ pub async fn payments_retrieve_with_gateway_creds()},&*auth_type,+ locking_action,).await}-/// Payments - Update////// To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created@@ -333,6 +346,8 @@ pub async fn payments_update(Err(err) => return api::log_and_return_error_response(report!(err)),};+ let locking_action = payload.get_locking_input(flow.clone());+api::server_wrap(flow,state,@@ -350,10 +365,10 @@ pub async fn payments_update()},&*auth_type,+ locking_action,).await}-/// Payments - Confirm////// This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments Create API@@ -406,6 +421,9 @@ pub async fn payments_confirm(Ok(auth) => auth,Err(e) => return api::log_and_return_error_response(e),};++ let locking_action = payload.get_locking_input(flow.clone());+api::server_wrap(flow,state,@@ -423,10 +441,10 @@ pub async fn payments_confirm()},&*auth_type,+ locking_action,).await}-/// Payments - Capture////// To capture the funds for an uncaptured payment@@ -454,16 +472,18 @@ pub async fn payments_capture(path: web::Path<String>,) -> impl Responder {let flow = Flow::PaymentsCapture;- let capture_payload = payment_types::PaymentsCaptureRequest {- payment_id: Some(path.into_inner()),+ let payload = payment_types::PaymentsCaptureRequest {+ payment_id: path.into_inner(),..json_payload.into_inner()};+ let locking_action = payload.get_locking_input(flow.clone());+api::server_wrap(flow,state,&req,- capture_payload,+ payload,|state, auth, payload| {payments::payments_core::<api_types::Capture, payment_types::PaymentsResponse, _, _, _>(state,@@ -477,10 +497,10 @@ pub async fn payments_capture()},&auth::ApiKeyAuth,+ locking_action,).await}-/// Payments - Session token////// To create the session object or to get session token for wallets@@ -503,13 +523,15 @@ pub async fn payments_connector_session(json_payload: web::Json<payment_types::PaymentsSessionRequest>,) -> impl Responder {let flow = Flow::PaymentsSessionToken;- let sessions_payload = json_payload.into_inner();+ let payload = json_payload.into_inner();++ let locking_action = payload.get_locking_input(flow.clone());api::server_wrap(flow,state,&req,- sessions_payload,+ payload,|state, auth, payload| {payments::payments_core::<api_types::Session,@@ -529,10 +551,10 @@ pub async fn payments_connector_session()},&auth::PublishableKeyAuth,+ locking_action,).await}-// /// Payments - Redirect response// ///// /// To get the payment response for redirect flows@@ -571,6 +593,7 @@ pub async fn payments_redirect_response(connector: Some(connector),creds_identifier: None,};+ let locking_action = payload.get_locking_input(flow.clone());api::server_wrap(flow,state,@@ -585,6 +608,7 @@ pub async fn payments_redirect_response()},&auth::MerchantIdAuth(merchant_id),+ locking_action,).await}@@ -626,6 +650,7 @@ pub async fn payments_redirect_response_with_creds_identifier(creds_identifier: Some(creds_identifier),};let flow = Flow::PaymentsRedirect;+ let locking_action = payload.get_locking_input(flow.clone());api::server_wrap(flow,state,@@ -640,10 +665,10 @@ pub async fn payments_redirect_response_with_creds_identifier()},&auth::MerchantIdAuth(merchant_id),+ locking_action,).await}-#[instrument(skip_all)]pub async fn payments_complete_authorize(state: web::Data<app::AppState>,@@ -664,6 +689,7 @@ pub async fn payments_complete_authorize(connector: Some(connector),creds_identifier: None,};+ let locking_action = payload.get_locking_input(flow.clone());api::server_wrap(flow,state,@@ -678,10 +704,10 @@ pub async fn payments_complete_authorize()},&auth::MerchantIdAuth(merchant_id),+ locking_action,).await}-/// Payments - Cancel////// A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action@@ -712,6 +738,7 @@ pub async fn payments_cancel(let mut payload = json_payload.into_inner();let payment_id = path.into_inner();payload.payment_id = payment_id;+ let locking_action = payload.get_locking_input(flow.clone());api::server_wrap(flow,state,@@ -730,10 +757,10 @@ pub async fn payments_cancel()},&auth::ApiKeyAuth,+ locking_action,).await}-/// Payments - List////// To list the payments@@ -775,10 +802,10 @@ pub async fn payments_list(payload,|state, auth, req| payments::list_payments(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]#[cfg(feature = "olap")]pub async fn payments_list_by_filter(@@ -795,10 +822,10 @@ pub async fn payments_list_by_filter(payload,|state, auth, req| payments::apply_filters_on_payments(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]#[cfg(feature = "olap")]pub async fn get_filters_for_payments(@@ -815,10 +842,10 @@ pub async fn get_filters_for_payments(payload,|state, auth, req| payments::get_filters_for_payments(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-async fn authorize_verify_select<Op>(operation: Op,state: app::AppState,@@ -875,3 +902,130 @@ where}}}++impl GetLockingInput for payment_types::PaymentsRequest {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ match self.payment_id {+ Some(payment_types::PaymentIdType::PaymentIntentId(ref id)) => {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+ _ => api_locking::LockAction::NotApplicable,+ }+ }+}++impl GetLockingInput for payment_types::PaymentsStartRequest {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: self.payment_id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+}++impl GetLockingInput for payment_types::PaymentsRetrieveRequest {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ match self.resource_id {+ payment_types::PaymentIdType::PaymentIntentId(ref id) => {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+ _ => api_locking::LockAction::NotApplicable,+ }+ }+}++impl GetLockingInput for payment_types::PaymentsSessionRequest {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: self.payment_id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+}++impl GetLockingInput for payments::PaymentsRedirectResponseData {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ match self.resource_id {+ payment_types::PaymentIdType::PaymentIntentId(ref id) => {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+ _ => api_locking::LockAction::NotApplicable,+ }+ }+}++impl GetLockingInput for payment_types::PaymentsCancelRequest {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: self.payment_id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+}++impl GetLockingInput for payment_types::PaymentsCaptureRequest {+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction+ where+ F: types::FlowMetric,+ lock_utils::ApiIdentifier: From<F>,+ {+ api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: self.payment_id.to_owned(),+ api_identifier: lock_utils::ApiIdentifier::from(flow),+ override_lock_retries: None,+ },+ }+ }+}diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rsindex 468b92030b..15cf59aaf3 100644--- a/crates/router/src/routes/payouts.rs+++ b/crates/router/src/routes/payouts.rs@@ -5,7 +5,10 @@ use actix_web::{use router_env::{instrument, tracing, Flow};use super::app::AppState;-use crate::services::{api, authentication as auth};+use crate::{+ core::api_locking,+ services::{api, authentication as auth},+};#[cfg(feature = "payouts")]use crate::{core::payouts::*, types::api::payouts as payout_types};@@ -37,10 +40,10 @@ pub async fn payouts_create(json_payload.into_inner(),|state, auth, req| payouts_create_core(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Payouts - Retrieve#[cfg(feature = "payouts")]#[utoipa::path(@@ -76,10 +79,10 @@ pub async fn payouts_retrieve(payout_retrieve_request,|state, auth, req| payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Payouts - Update#[cfg(feature = "payouts")]#[utoipa::path(@@ -115,10 +118,10 @@ pub async fn payouts_update(payout_update_payload,|state, auth, req| payouts_update_core(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Payouts - Cancel#[cfg(feature = "payouts")]#[utoipa::path(@@ -154,10 +157,10 @@ pub async fn payouts_cancel(payload,|state, auth, req| payouts_cancel_core(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Payouts - Fulfill#[cfg(feature = "payouts")]#[utoipa::path(@@ -193,10 +196,10 @@ pub async fn payouts_fulfill(payload,|state, auth, req| payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-#[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))]// #[get("/accounts")]pub async fn payouts_accounts() -> impl Responder {diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rsindex b5789c9a1e..4c4121b5d5 100644--- a/crates/router/src/routes/refunds.rs+++ b/crates/router/src/routes/refunds.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::refunds::*,+ core::{api_locking, refunds::*},services::{api, authentication as auth},types::api::refunds,};@@ -38,10 +38,10 @@ pub async fn refunds_create(json_payload.into_inner(),|state, auth, req| refund_create_core(state, auth.merchant_account, auth.key_store, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Refunds - Retrieve (GET)////// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment@@ -89,10 +89,10 @@ pub async fn refunds_retrieve()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Refunds - Retrieve (POST)////// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment@@ -130,10 +130,10 @@ pub async fn refunds_retrieve_with_body()},&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Refunds - Update////// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields@@ -169,10 +169,10 @@ pub async fn refunds_update(json_payload.into_inner(),|state, auth, req| refund_update_core(state, auth.merchant_account, &refund_id, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Refunds - List////// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided@@ -202,10 +202,10 @@ pub async fn refunds_list(payload.into_inner(),|state, auth, req| refund_list(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}-/// Refunds - Filter////// To list the refunds filters associated with list of connectors, currencies and payment statuses@@ -235,6 +235,7 @@ pub async fn refunds_filter_list(payload.into_inner(),|state, auth, req| refund_filter_list(state, auth.merchant_account, req),&auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rsindex 8173d00b84..a0861f2b14 100644--- a/crates/router/src/routes/verification.rs+++ b/crates/router/src/routes/verification.rs@@ -4,7 +4,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::verification,+ core::{api_locking, verification},services::{api, authentication as auth},};@@ -33,6 +33,7 @@ pub async fn apple_pay_merchant_registration()},auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}@@ -60,6 +61,7 @@ pub async fn retrieve_apple_pay_verified_domains()},auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rsindex c92b8bfd58..fa28e3fa7f 100644--- a/crates/router/src/routes/webhooks.rs+++ b/crates/router/src/routes/webhooks.rs@@ -3,7 +3,10 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::webhooks::{self, types},+ core::{+ api_locking,+ webhooks::{self, types},+ },services::{api, authentication as auth},};@@ -33,6 +36,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>()},&auth::MerchantIdAuth(merchant_id),+ api_locking::LockAction::NotApplicable,).await}diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex b10feebe16..432844afbe 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -26,6 +26,7 @@ use crate::{configs::settings::{Connectors, Settings},consts,core::{+ api_locking,errors::{self, CustomResult},payments,},@@ -712,6 +713,7 @@ pub async fn server_wrap_util<'a, 'b, A, U, T, Q, F, Fut, E, OErr>(payload: T,func: F,api_auth: &dyn auth::AuthenticateAndFetch<U, A>,+ lock_action: api_locking::LockAction,) -> CustomResult<ApplicationResponse<Q>, OErr>whereF: Fn(A, U, T) -> Fut,@@ -723,6 +725,7 @@ whereU: auth::AuthInfo,CustomResult<ApplicationResponse<Q>, E>: ReportSwitchExt<ApplicationResponse<Q>, OErr>,CustomResult<U, errors::ApiErrorResponse>: ReportSwitchExt<U, OErr>,+ CustomResult<(), errors::ApiErrorResponse>: ReportSwitchExt<(), OErr>,OErr: ResponseError + Sync + Send + 'static,{let request_id = RequestId::extract(request)@@ -750,7 +753,21 @@ wheretracing::Span::current().record("merchant_id", &merchant_id);- let output = func(request_state, auth_out, payload).await.switch();+ let output = {+ lock_action+ .clone()+ .perform_locking_action(&request_state, merchant_id.to_owned())+ .await+ .switch()?;+ let res = func(request_state.clone(), auth_out, payload)+ .await+ .switch();+ lock_action+ .free_lock_action(&request_state, merchant_id.to_owned())+ .await+ .switch()?;+ res+ };let status_code = match output.as_ref() {Ok(res) => metrics::request::track_response_status_code(res),@@ -773,6 +790,7 @@ pub async fn server_wrap<'a, A, T, U, Q, F, Fut, E>(payload: T,func: F,api_auth: &dyn auth::AuthenticateAndFetch<U, A>,+ lock_action: api_locking::LockAction,) -> HttpResponsewhereF: Fn(A, U, T) -> Fut,@@ -794,7 +812,15 @@ wherelogger::info!(tag = ?Tag::BeginRequest, payload = ?payload);let res = match metrics::request::record_request_time_metric(- server_wrap_util(&flow, state.clone(), request, payload, func, api_auth),+ server_wrap_util(+ &flow,+ state.clone(),+ request,+ payload,+ func,+ api_auth,+ lock_action,+ ),&flow,).awaitdiff --git a/crates/router/src/services/locking.rs b/crates/router/src/services/locking.rsdeleted file mode 100644index e69de29bb2..0000000000diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.jsonindex 33f86dab7b..2bce9585fd 100644--- a/openapi/openapi_spec.json+++ b/openapi/openapi_spec.json@@ -8339,11 +8339,13 @@},"PaymentsCaptureRequest": {"type": "object",+ "required": [+ "payment_id"+ ],"properties": {"payment_id": {"type": "string",- "description": "The unique identifier for the payment",- "nullable": true+ "description": "The unique identifier for the payment"},"merchant_id": {"type": "string",