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(payment-methods): invoke inline backward compat job (#12366)
Kashif2e6ca7e8cb62
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 10b780bb1a..22a8e321d2 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -151,6 +151,12 @@ schema = { type = "boolean" }description = "Whether to schedule PM modular backward compatibility PT for a merchant"change_reason = "Initial setup"+[default-configs.should_trigger_backwards_compatibility_inline]+value = false+schema = { type = "boolean" }+description = "Whether to trigger PM modular backward compatibility inline for a merchant"+change_reason = "Initial setup"+[default-configs.should_return_raw_payment_method_details]value = falseschema = { type = "boolean" }@@ -174,4 +180,3 @@ value = falseschema = { type = "boolean" }description = "Whether a specific incoming webhook event is disabled for a given connector"change_reason = "Initial setup"-diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rsindex 532677e5c6..2c9ed1f2b5 100644--- a/crates/diesel_models/src/payment_method.rs+++ b/crates/diesel_models/src/payment_method.rs@@ -91,6 +91,8 @@ pub struct PaymentMethod {pub payment_method_id: Option<String>,pub created_at: PrimitiveDateTime,pub last_modified: PrimitiveDateTime,+ pub payment_method: Option<storage_enums::PaymentMethod>,+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,pub payment_method_data: Option<Encryption>,pub locker_id: Option<String>,pub last_used_at: PrimitiveDateTime,@@ -192,6 +194,8 @@ pub struct PaymentMethodNew {pub payment_method_id: Option<String>,pub created_at: PrimitiveDateTime,pub last_modified: PrimitiveDateTime,+ pub payment_method: Option<storage_enums::PaymentMethod>,+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,pub payment_method_data: Option<Encryption>,pub locker_id: Option<String>,pub last_used_at: PrimitiveDateTime,@@ -384,6 +388,13 @@ pub enum PaymentMethodUpdate {locker_fingerprint_id: Option<String>,last_modified_by: Option<String>,},+ // Compatibility-only update used by modular backward-compat inline/PT.+ // Do not use this for normal v2 payment method updates.+ PopulateLegacyCompatFields {+ payment_method: Option<storage_enums::PaymentMethod>,+ payment_method_type: Option<storage_enums::PaymentMethodType>,+ last_modified_by: Option<String>,+ },}impl PaymentMethodUpdate {@@ -407,6 +418,8 @@ pub struct PaymentMethodUpdateInternal {network_transaction_link_id: Option<Secret<String>>,status: Option<storage_enums::PaymentMethodStatus>,locker_id: Option<String>,+ payment_method: Option<storage_enums::PaymentMethod>,+ payment_method_type: Option<storage_enums::PaymentMethodType>,payment_method_type_v2: Option<storage_enums::PaymentMethod>,connector_mandate_details: Option<CommonMandateReference>,updated_by: Option<String>,@@ -436,6 +449,8 @@ impl PaymentMethodUpdateInternal {updated_by,payment_method_subtype,last_modified,+ payment_method,+ payment_method_type,network_token_requestor_reference_id,network_token_locker_id,network_token_payment_method_data,@@ -450,6 +465,8 @@ impl PaymentMethodUpdateInternal {merchant_id: source.merchant_id,created_at: source.created_at,last_modified,+ payment_method: payment_method.or(source.payment_method),+ payment_method_type: payment_method_type.or(source.payment_method_type),payment_method_data: payment_method_data.or(source.payment_method_data),locker_id: locker_id.or(source.locker_id),last_used_at: last_used_at.unwrap_or(source.last_used_at),@@ -1048,6 +1065,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_transaction_link_id: None,status: None,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details: None,updated_by: None,@@ -1068,6 +1087,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_transaction_link_id: None,status: None,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details: None,updated_by: None,@@ -1093,6 +1114,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_transaction_link_id: None,status: None,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details: None,updated_by: None,@@ -1118,6 +1141,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_transaction_link_id,status,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details: None,updated_by: None,@@ -1141,6 +1166,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_transaction_link_id: None,status,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details: None,updated_by: None,@@ -1174,6 +1201,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {last_used_at: None,status,locker_id,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2,connector_mandate_details: *connector_mandate_details,updated_by: None,@@ -1197,6 +1226,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {last_used_at: None,status: None,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details,network_transaction_id: None,@@ -1223,6 +1254,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_transaction_link_id: None,status,locker_id: None,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: None,connector_mandate_details: None,updated_by: None,@@ -1236,6 +1269,32 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {last_modified_by,customer_details: None,},+ PaymentMethodUpdate::PopulateLegacyCompatFields {+ payment_method,+ payment_method_type,+ last_modified_by,+ } => Self {+ payment_method_data: None,+ last_used_at: None,+ network_transaction_id: None,+ network_transaction_link_id: None,+ status: None,+ locker_id: None,+ payment_method,+ payment_method_type,+ payment_method_type_v2: None,+ connector_mandate_details: None,+ updated_by: None,+ payment_method_subtype: None,+ last_modified: common_utils::date_time::now(),+ network_token_locker_id: None,+ network_token_requestor_reference_id: None,+ network_token_payment_method_data: None,+ locker_fingerprint_id: None,+ external_vault_source: None,+ last_modified_by,+ customer_details: None,+ },}}}@@ -1308,6 +1367,8 @@ impl From<&PaymentMethodNew> for PaymentMethod {locker_id: payment_method_new.locker_id.clone(),created_at: payment_method_new.created_at,last_modified: payment_method_new.last_modified,+ payment_method: payment_method_new.payment_method,+ payment_method_type: payment_method_new.payment_method_type,payment_method_data: payment_method_new.payment_method_data.clone(),last_used_at: payment_method_new.last_used_at,connector_mandate_details: payment_method_new.connector_mandate_details.clone(),diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 944f60a7ac..613ba28d9f 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -1334,6 +1334,9 @@ diesel::table! {payment_method_id -> Nullable<Varchar>,created_at -> Timestamp,last_modified -> Timestamp,+ payment_method -> Nullable<Varchar>,+ #[max_length = 64]+ payment_method_type -> Nullable<Varchar>,payment_method_data -> Nullable<Bytea>,#[max_length = 64]locker_id -> Nullable<Varchar>,diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex c4787ac3b4..69cbe46f41 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -757,6 +757,8 @@ impl super::behaviour::Conversion for PaymentMethod {payment_method_id: Some(payment_method_id),created_at: self.created_at,last_modified: self.last_modified,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: self.payment_method_type,payment_method_subtype: self.payment_method_subtype,payment_method_data: self.payment_method_data.map(|val| val.into()),@@ -950,6 +952,8 @@ impl super::behaviour::Conversion for PaymentMethod {payment_method_id: Some(payment_method_id),created_at: self.created_at,last_modified: self.last_modified,+ payment_method: None,+ payment_method_type: None,payment_method_type_v2: self.payment_method_type,payment_method_subtype: self.payment_method_subtype,payment_method_data: self.payment_method_data.map(|val| val.into()),diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 3775097e65..499259b884 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -388,6 +388,9 @@ pub mod superposition {/// Schedule PM modular backward compatibility PT configuration keypub const SHOULD_SCHEDULE_MODULAR_BACKWARD_COMPAT: &str ="should_schedule_modular_backward_compat";+ /// Trigger PM modular backward compatibility inline configuration key+ pub const SHOULD_TRIGGER_BACKWARDS_COMPATIBILITY_INLINE: &str =+ "should_trigger_backwards_compatibility_inline";/// dynamic fields configuration key for sdk configpub const DYNAMIC_FIELDS: &str = "dynamic_fields";/// payout sync tracker configuration keydiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 4539f15752..d131741183 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -469,6 +469,24 @@ impl DatabaseBackedConfig for ShouldScheduleModularBackwardCompat {}}+config! {+ superposition_key = SHOULD_TRIGGER_BACKWARDS_COMPATIBILITY_INLINE,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProviderMerchantId,+ targeting_key = id_type::CustomerId+}++impl DatabaseBackedConfig for ShouldTriggerBackwardsCompatibilityInline {+ const KEY: &'static str = "should_trigger_backwards_compatibility_inline";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_provider_merchant_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+config! {superposition_key = PAYOUT_TRACKER_MAPPING,output = RetryMapping,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex d58c855766..7decfb09fc 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -1,4 +1,6 @@pub mod access_token;+#[cfg(feature = "v2")]+mod backward_compat;#[cfg(feature = "v1")]pub mod batch_retrieve;pub mod cards;@@ -2642,52 +2644,14 @@ async fn execute_payment_method_create(None,)?;- let merchant_id = platform.get_provider().get_account().get_id().to_owned();- let should_schedule_modular_backward_compat =- utils::get_should_schedule_modular_backward_compat(+ Box::pin(+ backward_compat::trigger_payment_method_modular_backward_compat_best_effort(state,- &dimension_state::Dimensions::new().with_provider_merchant_id(- platform.get_provider().get_provider_merchant_id(),- ),- None,- )- .await;-- if should_schedule_modular_backward_compat {- let res = add_payment_method_modular_backward_compat_task(- &*state.store,&payment_method,- &merchant_id,- state.conf.application_source,- platform.get_initiator(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to add payment method modular backward compatibility task in process tracker",- );-- if let Err(err) = res {- logger::error!(- ?err,- payment_method_id = %payment_method.get_id().get_string_repr(),- merchant_id=%merchant_id.get_string_repr(),- "Failed to schedule modular backward compatibility PT; continuing payment method create flow"- );- } else {- logger::info!(- payment_method_id = %payment_method.get_id().get_string_repr(),- merchant_id=%merchant_id.get_string_repr(),- "Scheduled payment method modular backward compatibility PT"- );- }- } else {- logger::debug!(- payment_method_id = %payment_method.get_id().get_string_repr(),- merchant_id=%merchant_id.get_string_repr(),- "Skipping modular backward compatibility PT scheduling by config"- );- }+ platform,+ ),+ )+ .await;Ok((resp, payment_method))}diff --git a/crates/router/src/core/payment_methods/backward_compat.rs b/crates/router/src/core/payment_methods/backward_compat.rsnew file mode 100644index 0000000000..8410c86191--- /dev/null+++ b/crates/router/src/core/payment_methods/backward_compat.rs@@ -0,0 +1,146 @@+use common_utils::{ext_traits::StringExt, id_type};+use error_stack::ResultExt;++use super::{add_payment_method_modular_backward_compat_task, utils};+use crate::{+ core::{configs::dimension_state, errors::ProcessTrackerError},+ errors as router_errors, logger,+ routes::SessionState,+ types::{domain, storage},+};++async fn trigger_payment_method_modular_backward_compat_inline(+ state: &SessionState,+ payment_method: &domain::PaymentMethod,+ merchant_id: &id_type::MerchantId,+ initiator: Option<&hyperswitch_domain_models::platform::Initiator>,+) -> Result<(), ProcessTrackerError> {+ let tracking_data = storage::PaymentMethodModularCompatTrackingData {+ payment_method_id: payment_method.get_id().get_string_repr().to_owned(),+ merchant_id: merchant_id.to_owned(),+ last_modified_by: initiator+ .and_then(|initiator| initiator.to_created_by())+ .map(|last_modified_by| last_modified_by.to_string()),+ };++ Box::pin(+ crate::workflows::payment_method_modular_backward_compat::run_payment_method_modular_backward_compat_backfill(+ state,+ tracking_data,+ "INLINE_PM_MOD_BACK_COMPAT",+ ),+ )+ .await+}++async fn schedule_payment_method_modular_backward_compat_task_best_effort(+ state: &SessionState,+ payment_method: &domain::PaymentMethod,+ merchant_id: &id_type::MerchantId,+ initiator: Option<&hyperswitch_domain_models::platform::Initiator>,+) {+ let res = add_payment_method_modular_backward_compat_task(+ &*state.store,+ payment_method,+ merchant_id,+ state.conf.application_source,+ initiator,+ )+ .await+ .change_context(router_errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to add payment method modular backward compatibility task in process tracker",+ );++ if let Err(err) = res {+ logger::error!(+ ?err,+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Failed to schedule modular backward compatibility PT; continuing payment method create flow"+ );+ } else {+ logger::info!(+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Scheduled payment method modular backward compatibility PT"+ );+ }+}++pub(super) async fn trigger_payment_method_modular_backward_compat_best_effort(+ state: &SessionState,+ payment_method: &domain::PaymentMethod,+ platform: &domain::Platform,+) {+ let merchant_id = platform.get_provider().get_account().get_id().to_owned();+ let dimensions = dimension_state::Dimensions::new()+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());+ let should_trigger_backwards_compatibility_inline =+ utils::get_should_trigger_backwards_compatibility_inline(state, &dimensions, None).await;++ if should_trigger_backwards_compatibility_inline {+ let inline_result = tokio::time::timeout(+ std::time::Duration::from_secs(3),+ Box::pin(trigger_payment_method_modular_backward_compat_inline(+ state,+ payment_method,+ &merchant_id,+ platform.get_initiator(),+ )),+ )+ .await;++ match inline_result {+ Ok(Ok(())) => {+ logger::info!(+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Completed modular backward compatibility inline"+ );+ }+ Ok(Err(err)) => {+ logger::error!(+ ?err,+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Failed modular backward compatibility inline; continuing payment method create flow"+ );+ }+ Err(err) => {+ logger::error!(+ ?err,+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Timed out modular backward compatibility inline; scheduling PT fallback"+ );+ schedule_payment_method_modular_backward_compat_task_best_effort(+ state,+ payment_method,+ &merchant_id,+ platform.get_initiator(),+ )+ .await;+ }+ }+ } else {+ let should_schedule_modular_backward_compat =+ utils::get_should_schedule_modular_backward_compat(state, &dimensions, None).await;++ if should_schedule_modular_backward_compat {+ schedule_payment_method_modular_backward_compat_task_best_effort(+ state,+ payment_method,+ &merchant_id,+ platform.get_initiator(),+ )+ .await;+ } else {+ logger::debug!(+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Skipping modular backward compatibility PT scheduling by config"+ );+ }+ }+}diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex dc703292fd..452149314e 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -853,6 +853,20 @@ pub async fn get_should_schedule_modular_backward_compat(.await}+pub async fn get_should_trigger_backwards_compatibility_inline(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProviderMerchantId,+ customer_id: Option<&common_utils::id_type::CustomerId>,+) -> bool {+ dimensions+ .get_should_trigger_backwards_compatibility_inline(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ customer_id,+ )+ .await+}+pub async fn get_sdk_next_action_for_payment_method_list(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rsindex bfe32dfd11..16e1ee7fab 100644--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs@@ -1,13 +1,20 @@+#[cfg(feature = "v1")]use api_models::payment_methods::Card;use common_utils::ext_traits::{Encode, OptionExt, StringExt, ValueExt};+#[cfg(feature = "v2")]+use common_utils::id_type;use error_stack::ResultExt;use hyperswitch_masking::PeekInterface;use scheduler::{consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,};+#[cfg(feature = "v2")]+use crate::core::payment_methods::add_payment_method_to_legacy_locker;+#[cfg(feature = "v1")]+use crate::core::payment_methods::transformers;use crate::{- core::payment_methods::{cards, transformers, vault},+ core::payment_methods::{cards, vault},errors,logger::{self, error},routes::{app::StorageInterface, SessionState},@@ -18,7 +25,7 @@ use crate::{};#[cfg(feature = "v1")]-async fn backfill_legacy_db_fields(+pub async fn backfill_legacy_db_fields(db: &dyn StorageInterface,key_store: &domain::MerchantKeyStore,payment_method: domain::PaymentMethod,@@ -57,8 +64,48 @@ async fn backfill_legacy_db_fields(}}+#[cfg(feature = "v2")]+pub async fn backfill_legacy_db_fields(+ db: &dyn StorageInterface,+ key_store: &domain::MerchantKeyStore,+ payment_method: domain::PaymentMethod,+ storage_scheme: common_enums::MerchantStorageScheme,+ tracking_data: &PaymentMethodModularCompatTrackingData,+ process_id: &str,+) -> Result<domain::PaymentMethod, errors::ProcessTrackerError> {+ let legacy_payment_method = payment_method.get_payment_method_type();+ let legacy_payment_method_type = payment_method.get_payment_method_subtype();+ let should_update_legacy_db_fields =+ legacy_payment_method.is_some() || legacy_payment_method_type.is_some();++ if should_update_legacy_db_fields {+ let pm_update = storage::PaymentMethodUpdate::PopulateLegacyCompatFields {+ payment_method: legacy_payment_method,+ payment_method_type: legacy_payment_method_type,+ last_modified_by: tracking_data.last_modified_by.clone(),+ };++ let updated_payment_method = db+ .update_payment_method(key_store, payment_method, pm_update, storage_scheme)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to populate legacy payment method fields in backward compatibility inline flow",+ )?;++ Ok(updated_payment_method)+ } else {+ logger::info!(+ process_id=%process_id,+ payment_method_id=%tracking_data.payment_method_id,+ "Skipping legacy DB field backfill in modular backward compatibility inline flow because fields are already populated"+ );+ Ok(payment_method)+ }+}+#[cfg(feature = "v1")]-async fn backfill_legacy_locker_card(+pub async fn backfill_legacy_locker_card(state: &SessionState,merchant_id: &common_utils::id_type::MerchantId,payment_method: &domain::PaymentMethod,@@ -206,69 +253,258 @@ async fn backfill_legacy_locker_card(Ok(())}-pub struct PaymentMethodModularBackwardCompatWorkflow;--#[async_trait::async_trait]-impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularBackwardCompatWorkflow {- #[cfg(feature = "v1")]- async fn execute_workflow<'a>(- &'a self,- state: &'a SessionState,- process: storage::ProcessTracker,- ) -> Result<(), errors::ProcessTrackerError> {- logger::info!(process_id=%process.id, "Starting payment method modular backward compatibility PT");- let db = &*state.store;- let tracking_data: PaymentMethodModularCompatTrackingData =- process- .tracking_data- .clone()- .parse_value("PaymentMethodModularCompatTrackingData")?;- logger::info!(process_id=%process.id, ?tracking_data, "Parsed modular backward compatibility PT tracking data");+#[cfg(feature = "v2")]+pub async fn backfill_legacy_locker_card(+ state: &SessionState,+ platform: &domain::Platform,+ payment_method: &domain::PaymentMethod,+ tracking_data: &PaymentMethodModularCompatTrackingData,+ process_id: &str,+) -> Result<(), errors::ProcessTrackerError> {+ let legacy_locker_skip_reason = match (+ payment_method.get_payment_method_type(),+ payment_method.locker_id.as_ref(),+ payment_method.customer_id.as_ref(),+ ) {+ (Some(common_enums::PaymentMethod::Card), Some(_), Some(_)) => None,+ (Some(common_enums::PaymentMethod::Card), None, _) => Some("locker reference is missing"),+ (Some(common_enums::PaymentMethod::Card), Some(_), None) => Some("customer_id is missing"),+ _ => Some("payment method is not card"),+ };- let merchant_id = tracking_data.merchant_id.clone();- let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),+ if let Some(skip_reason) = legacy_locker_skip_reason {+ logger::info!(+ process_id=%process_id,+ payment_method_id=%tracking_data.payment_method_id,+ skip_reason,+ "Skipping legacy locker card backfill in modular backward compatibility inline flow"+ );+ } else {+ let customer_id = payment_method+ .customer_id+ .clone()+ .get_required_value("customer_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "customer_id not found for card payment method in backward compatibility inline flow",)- .await?;+ .and_then(|customer_id| {+ id_type::CustomerId::try_from(customer_id)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to convert global customer id for backward compatibility inline flow",+ )+ })?;- let merchant_account = db- .find_merchant_account_by_merchant_id(&merchant_id, &key_store)- .await?;+ let card_reference = payment_method+ .locker_id+ .clone()+ .get_required_value("locker_id")?+ .get_string_repr()+ .to_owned();++ let legacy_card_exists = match cards::get_card_from_locker(+ state,+ &customer_id,+ platform.get_provider().get_account().get_id(),+ &card_reference,+ )+ .await+ {+ Ok(_) => {+ logger::info!(+ process_id=%process_id,+ payment_method_id=%tracking_data.payment_method_id,+ card_reference=%card_reference,+ "Skipping legacy locker write in modular backward compatibility inline flow because card already exists"+ );+ true+ }+ Err(err) => {+ logger::info!(+ ?err,+ process_id=%process_id,+ payment_method_id=%tracking_data.payment_method_id,+ card_reference=%card_reference,+ "Legacy locker card not found or not readable in modular backward compatibility inline flow; proceeding with legacy locker upsert"+ );+ false+ }+ };- let payment_method = db- .find_payment_method(- &key_store,- &tracking_data.payment_method_id,- merchant_account.storage_scheme,+ if !legacy_card_exists {+ let vault_request = pm_types::GenericVaultRetrieveRequest {+ entity_id: customer_id.clone(),+ vault_id: domain::VaultId::generate(card_reference.clone()),+ };+ let payload = vault_request+ .encode_to_vec()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to encode generic locker retrieve request in backward compatibility inline flow",+ )?;+ let vault_response = vault::call_to_vault::<pm_types::VaultRetrieve>(+ state, payload, None,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable(- "Failed to fetch payment method for modular backward compatibility PT",+ "Failed to retrieve card from generic locker in backward compatibility inline flow",+ )?;+ let stored_pm_resp: pm_types::VaultRetrieveResponse = vault_response+ .parse_struct("VaultRetrieveResponse")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to parse generic locker retrieve response in backward compatibility inline flow",+ )?;+ if !matches!(+ stored_pm_resp.data,+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(_)+ ) {+ Err(+ error_stack::report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Generic locker returned non-card data in backward compatibility inline flow",+ ),+ )?+ }++ let _ = add_payment_method_to_legacy_locker(+ state,+ platform,+ &stored_pm_resp.data,+ Some(domain::VaultId::generate(card_reference.clone())),+ payment_method+ .customer_id+ .as_ref()+ .get_required_value("customer_id")?,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to add card to legacy locker in backward compatibility inline flow",)?;- let payment_method = backfill_legacy_db_fields(- db,+ logger::info!(+ process_id=%process_id,+ payment_method_id=%tracking_data.payment_method_id,+ "Upserted card into legacy locker in modular backward compatibility inline flow"+ );+ }+ }++ Ok(())+}++pub async fn run_payment_method_modular_backward_compat_backfill(+ state: &SessionState,+ tracking_data: PaymentMethodModularCompatTrackingData,+ process_id: &str,+) -> Result<(), errors::ProcessTrackerError> {+ let db = &*state.store;+ let merchant_id = tracking_data.merchant_id.clone();+ let key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ &merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await?;++ let merchant_account = db+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)+ .await?;++ #[cfg(feature = "v1")]+ let payment_method_id = tracking_data.payment_method_id.as_str();+ #[cfg(feature = "v2")]+ let payment_method_id = id_type::GlobalPaymentMethodId::generate_from_string(+ tracking_data.payment_method_id.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to parse payment method id for modular backward compatibility backfill",+ )?;++ let payment_method = db+ .find_payment_method(&key_store,- payment_method,+ #[cfg(feature = "v1")]+ payment_method_id,+ #[cfg(feature = "v2")]+ &payment_method_id,merchant_account.storage_scheme,- &tracking_data,- &process.id,)- .await?;+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to fetch payment method for modular backward compatibility backfill",+ )?;+ let payment_method = backfill_legacy_db_fields(+ db,+ &key_store,+ payment_method,+ merchant_account.storage_scheme,+ &tracking_data,+ process_id,+ )+ .await?;++ #[cfg(feature = "v1")]+ {backfill_legacy_locker_card(state,&merchant_id,&payment_method,&tracking_data,- &process.id,+ process_id,)- .await?;+ .await+ }++ #[cfg(feature = "v2")]+ {+ let platform = domain::Platform::new(+ merchant_account.clone(),+ key_store.clone(),+ merchant_account,+ key_store,+ None,+ );+ backfill_legacy_locker_card(+ state,+ &platform,+ &payment_method,+ &tracking_data,+ process_id,+ )+ .await+ }+}+pub struct PaymentMethodModularBackwardCompatWorkflow;++#[async_trait::async_trait]+impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularBackwardCompatWorkflow {+ #[cfg(feature = "v1")]+ async fn execute_workflow<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ logger::info!(process_id=%process.id, "Starting payment method modular backward compatibility PT");+ let tracking_data: PaymentMethodModularCompatTrackingData =+ process+ .tracking_data+ .clone()+ .parse_value("PaymentMethodModularCompatTrackingData")?;+ logger::info!(process_id=%process.id, ?tracking_data, "Parsed modular backward compatibility PT tracking data");++ run_payment_method_modular_backward_compat_backfill(state, tracking_data, &process.id)+ .await?;++ let db = &*state.store;db.as_scheduler().finish_process_with_business_status(process, "COMPLETED_BY_PT").await?;diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sqlindex 9fe4f9a149..1101b75e5f 100644--- a/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql+++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql@@ -122,8 +122,6 @@ ALTER TABLE payment_methodsADD COLUMN IF NOT EXISTS swift_code VARCHAR(32),ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128),ADD COLUMN IF NOT EXISTS metadata JSON,- ADD COLUMN IF NOT EXISTS payment_method VARCHAR,- ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64),ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode";ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512),diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sqlindex b73e98b1fc..0c4e3f8048 100644--- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql+++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql@@ -110,9 +110,7 @@ ALTER TABLE payment_methodsDROP COLUMN IF EXISTS swift_code,DROP COLUMN IF EXISTS payment_method_issuer,DROP COLUMN IF EXISTS payment_method_issuer_code,- DROP COLUMN IF EXISTS metadata,- DROP COLUMN IF EXISTS payment_method,- DROP COLUMN IF EXISTS payment_method_type;+ DROP COLUMN IF EXISTS metadata;DROP TYPE IF EXISTS "PaymentMethodIssuerCode";-- Run below queries only when V1 is deprecated