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
refactor(payment_methods): add network tokenization pt job in modular payment method apis (#13489)
Prasunna Soppa1731313cc218
diff --git a/Cargo.lock b/Cargo.lockindex ca185a378f..2c2a04d0af 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4791,6 +4791,7 @@ dependencies = ["common_utils","dyn-clone","error-stack 0.4.1",+ "futures 0.3.31","http 0.2.12","hyperswitch_domain_models","hyperswitch_masking",diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex ffe375e6ae..cc3e739170 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2652,6 +2652,7 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen"payments.should_enable_mit_with_limited_card_data" = { value = false, schema = { type = "boolean" }, description = "Whether to allow merchant-initiated transactions (MIT) with limited card data", change_reason = "Initial setup" }"payments.should_perform_eligibility" = { value = false, schema = { type = "boolean" }, description = "Whether the SDK should perform an eligibility check before confirming payment", change_reason = "Initial setup" }"payments.should_return_raw_payment_method_details" = { value = false, schema = { type = "boolean" }, description = "Whether to return raw payment method details (v2 only)", change_reason = "Initial setup" }+"payments.network_token_fetch_timeout_in_secs" = { value = 4, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Timeout in seconds for network token fetch", change_reason = "Initial setup" }should_schedule_modular_backward_compat = { value = false, schema = { type = "boolean" }, description = "Whether to schedule PM modular backward compatibility PT for a provider merchant, with organization fallback", change_reason = "Initial setup" }"system.should_schedule_modular_forward_compat" = { value = false, schema = { type = "boolean" }, description = "Whether to schedule PM modular forward compatibility PT for a provider merchant, with organization fallback", change_reason = "Initial setup" }"payments.should_store_eligibility_check_data_for_authentication" = { value = false, schema = { type = "boolean" }, description = "Whether to store eligibility check data during authentication", change_reason = "Initial setup" }diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex 96a942774d..24a89aed75 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -22,6 +22,7 @@ async-trait = "0.1.88"bytes = "1.10.1"dyn-clone = "1.0.19"error-stack = "0.4.1"+futures = "0.3.31"http = "0.2.12"mime = "0.3.17"prost = "0.14"diff --git a/crates/hyperswitch_interfaces/src/api_client.rs b/crates/hyperswitch_interfaces/src/api_client.rsindex 382e170aa5..becce081ac 100644--- a/crates/hyperswitch_interfaces/src/api_client.rs+++ b/crates/hyperswitch_interfaces/src/api_client.rs@@ -14,6 +14,7 @@ use common_utils::{request::{Headers, Request, RequestContent},};use error_stack::{report, ResultExt};+use futures::FutureExt;use http::Method;use hyperswitch_domain_models::{errors::api_error_response,@@ -287,9 +288,13 @@ wherelet request_url = request.url.clone();let request_method = request.method;let current_time = Instant::now();- let response =- call_connector_api(state, request, "execute_connector_processing_step")- .await;+ let response = call_connector_api(+ state,+ request,+ "execute_connector_processing_step",+ None,+ )+ .await;let external_latency = current_time.elapsed().as_millis();logger::info!(raw_connector_request=?masked_request_body);let status_code = response@@ -495,53 +500,61 @@ pub async fn call_connector_api(state: &dyn ApiClientWrapper,request: Request,flow_name: &str,+ option_timeout_secs: Option<u64>,) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> {- let current_time = Instant::now();- let headers = request.headers.clone();- let url = request.url.clone();- #[cfg(feature = "ext_services_latency")]- let method = request.method.to_string();- let response = state- .get_api_client()- .send_request(state, request, None, true)- .await;-- #[cfg(feature = "ext_services_latency")]- if let Ok(resp) = response.as_ref() {- let downstream_request_id = resp- .headers()- .get(X_REQUEST_ID)- .and_then(|value| value.to_str().ok());- logger::info!(- tag = EXTERNAL_CALL_TAG,- operation = flow_name,- method,- status_code = resp.status().as_u16(),- latency_ms = current_time.elapsed().as_secs_f64() * 1000.0,- downstream_request_id,- );- }-- match response.as_ref() {- Ok(resp) => {- let status_code = resp.status().as_u16();- let elapsed_time = current_time.elapsed();+ // The `reqwest::Response` held across awaits nests decompression internals deeply+ // enough to overflow the compiler's trait recursion limit when this future's type+ // is composed into callers' futures, so it is erased behind a boxed trait object+ async move {+ let current_time = Instant::now();+ let headers = request.headers.clone();+ let url = request.url.clone();+ #[cfg(feature = "ext_services_latency")]+ let method = request.method.to_string();+ let response = state+ .get_api_client()+ .send_request(state, request, option_timeout_secs, true)+ .await;++ #[cfg(feature = "ext_services_latency")]+ if let Ok(resp) = response.as_ref() {+ let downstream_request_id = resp+ .headers()+ .get(X_REQUEST_ID)+ .and_then(|value| value.to_str().ok());logger::info!(- ?headers,- url,- status_code,- flow=?flow_name,- ?elapsed_time+ tag = EXTERNAL_CALL_TAG,+ operation = flow_name,+ method,+ status_code = resp.status().as_u16(),+ latency_ms = current_time.elapsed().as_secs_f64() * 1000.0,+ downstream_request_id,);}- Err(err) => {- logger::info!(- call_connector_api_error=?err- );++ match response.as_ref() {+ Ok(resp) => {+ let status_code = resp.status().as_u16();+ let elapsed_time = current_time.elapsed();+ logger::info!(+ ?headers,+ url,+ status_code,+ flow=?flow_name,+ ?elapsed_time+ );+ }+ Err(err) => {+ logger::info!(+ call_connector_api_error=?err+ );+ }}- }- handle_response(response).await+ handle_response(response).await+ }+ .boxed()+ .await}/// Handle the response from the API calldiff --git a/crates/hyperswitch_interfaces/src/micro_service/executor.rs b/crates/hyperswitch_interfaces/src/micro_service/executor.rsindex 48c89c55ff..f5fa913742 100644--- a/crates/hyperswitch_interfaces/src/micro_service/executor.rs+++ b/crates/hyperswitch_interfaces/src/micro_service/executor.rs@@ -117,7 +117,7 @@ impl<O: ClientOperation> TransformedRequest<O> {}// Step 4: Execute request and decode response.- let response = call_connector_api(state, http_request, operation)+ let response = call_connector_api(state, http_request, operation, None).await.map_err(|e| {logger::error!(operation, error = ?e, "microservice request failed");diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex f84ba50d54..1f0d24f48a 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -434,6 +434,10 @@ pub mod superposition {/// Trigger fingerprint migration configuration keypub const SHOULD_TRIGGER_FINGERPRINT_MIGRATION: &str ="vaulting.should_trigger_fingerprint_migration";+ /// Timeout (in seconds) for fetching a network token from the tokenization service during a+ /// payment configuration key+ pub const NETWORK_TOKEN_FETCH_TIMEOUT_IN_SECS: &str =+ "payments.network_token_fetch_timeout_in_secs";/// Perform SDK vaulting action configuration key. Acts as a merchant level override on top of/// `should_call_pm_modular_service`: defaults to `true` for all merchants and can be set to/// `false` for specific merchants to force the SDK to skip tokenization.diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 5836109be1..18c2d22efd 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -454,6 +454,23 @@ impl DatabaseBackedConfig for ShouldTriggerFingerprintMigration {}}+config! {+ superposition_key = NETWORK_TOKEN_FETCH_TIMEOUT_IN_SECS,+ output = u32,+ default = 4,+ requires = dimension_state::DimensionsGlobal,+ targeting_key = id_type::CustomerId+}++impl DatabaseBackedConfig for NetworkTokenFetchTimeoutInSecs {+ const KEY: &'static str = "network_token_fetch_timeout_in_secs";++ // Global config: a single deployment-wide key, not scoped to any merchant.+ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ Some(Self::KEY.to_string())+ }+}+config! {superposition_key = SHOULD_PERFORM_SDK_VAULTING,output = bool,diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rsindex f6ba0de550..2d5cf7a329 100644--- a/crates/router/src/core/health_check.rs+++ b/crates/router/src/core/health_check.rs@@ -92,7 +92,7 @@ impl HealthCheckInterface for app::SessionState {let mut url = locker.host.to_owned();url.push_str(consts::LOCKER_HEALTH_CALL_PATH);let request = services::Request::new(services::Method::Get, &url);- services::call_connector_api(self, request, "health_check_for_locker")+ services::call_connector_api(self, request, "health_check_for_locker", None).await.change_context(errors::HealthCheckLockerError::FailedToCallLocker)?.map_err(|_| {@@ -162,7 +162,7 @@ impl HealthCheckInterface for app::SessionState {&self,) -> CustomResult<HealthState, errors::HealthCheckOutGoing> {let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL);- services::call_connector_api(self, request, "outgoing_health_check")+ services::call_connector_api(self, request, "outgoing_health_check", None).await.map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {message: err.to_string(),@@ -201,11 +201,16 @@ impl HealthCheckInterface for app::SessionState {if self.conf.open_router.dynamic_routing_enabled {let url = format!("{}/{}", self.conf.open_router.url, "health");let request = services::Request::new(services::Method::Get, &url);- let _ = services::call_connector_api(self, request, "health_check_for_decision_engine")- .await- .change_context(- errors::HealthCheckDecisionEngineError::FailedToCallDecisionEngineService,- )?;+ let _ = services::call_connector_api(+ self,+ request,+ "health_check_for_decision_engine",+ None,+ )+ .await+ .change_context(+ errors::HealthCheckDecisionEngineError::FailedToCallDecisionEngineService,+ )?;logger::debug!("Decision engine health check successful");Ok(HealthState::Running)diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 2b72c88aa6..34ee828636 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -126,9 +126,10 @@ const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_MAX_LENGTH: usize = 126;const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_SUFFIX_LENGTH: usize = 8;#[cfg(feature = "v2")]const PAYMENT_METHOD_REDACTED_FINGERPRINT_ID: &str = "FINGERPRINT_ID_REDACTED";-#[cfg(feature = "v1")]+/// `process_tracker.id` is a `varchar(127)`; ids are built to stay within it.+const NETWORK_TOKENIZATION_PROCESS_TRACKER_ID_MAX_LENGTH: usize = 126;+const NETWORK_TOKENIZATION_PROCESS_TRACKER_ID_SUFFIX_LENGTH: usize = 8;const NETWORK_TOKENIZATION_TASK: &str = "NETWORK_TOKENIZATION";-#[cfg(feature = "v1")]const NETWORK_TOKENIZATION_TAG: &str = "NETWORK_TOKENIZATION";#[instrument(skip_all)]@@ -502,6 +503,27 @@ fn generate_task_id_for_payment_method_modular_compat_workflow(format!("{prefix}{key_id}_{suffix}")}+/// Builds the `process_tracker` id for a `NetworkTokenizationWorkflow` task.+///+/// The random suffix keeps the id unique so that a payment method whose earlier task already+/// reached a terminal state can be scheduled again — finished rows are retained, so a+/// deterministic id would make every later attempt a silent no-op. The payment method id is+/// truncated to keep the result within the `varchar(127)` `process_tracker.id` column.+fn generate_task_id_for_network_tokenization_workflow(+ payment_method_id: &str,+ runner: storage::ProcessTrackerRunner,+ task: &str,+) -> String {+ let suffix =+ common_utils::generate_id_with_len(NETWORK_TOKENIZATION_PROCESS_TRACKER_ID_SUFFIX_LENGTH);+ let prefix = format!("{runner}_{task}_");+ let payment_method_id_len = NETWORK_TOKENIZATION_PROCESS_TRACKER_ID_MAX_LENGTH+ .saturating_sub(prefix.len() + suffix.len() + 1);+ let payment_method_id =+ &payment_method_id[..payment_method_id.len().min(payment_method_id_len)];+ format!("{prefix}{payment_method_id}_{suffix}")+}+fn payment_method_compat_modifier(payment_method: &domain::PaymentMethod) -> Option<String> {payment_method.last_modified_by@@ -725,7 +747,11 @@ pub async fn add_network_tokenization_task(let runner = storage::ProcessTrackerRunner::NetworkTokenizationWorkflow;let task = NETWORK_TOKENIZATION_TASK;let tag = [NETWORK_TOKENIZATION_TAG];- let process_tracker_id = format!("{runner}_{task}_{payment_method_id}");+ // The task id carries a unique suffix so that a payment method whose earlier task already+ // finished (completed, retries exceeded or skipped) can be scheduled again; runs against an+ // already-tokenized payment method finish as a no-op in the workflow itself.+ let process_tracker_id =+ generate_task_id_for_network_tokenization_workflow(&payment_method_id, runner, task);let process_tracker_entry = storage::ProcessTrackerNew::new(process_tracker_id,@@ -743,6 +769,7 @@ pub async fn add_network_tokenization_task(db.insert_process(process_tracker_entry).await+ .map(|_| ()).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| {format!(@@ -753,6 +780,105 @@ pub async fn add_network_tokenization_task(Ok(())}+#[cfg(feature = "v2")]+pub async fn add_network_tokenization_task(+ db: &dyn StorageInterface,+ tracking_data: storage::NetworkTokenizationTrackingData,+ application_source: common_enums::ApplicationSource,+) -> Result<(), ProcessTrackerError> {+ let payment_method_id = tracking_data.payment_method_id.get_string_repr().to_owned();++ let runner = storage::ProcessTrackerRunner::NetworkTokenizationWorkflow;+ let task = NETWORK_TOKENIZATION_TASK;+ let tag = [NETWORK_TOKENIZATION_TAG];+ // The task id carries a unique suffix so that a payment method whose earlier task already+ // finished (completed, retries exceeded or skipped) can be scheduled again; runs against an+ // already-tokenized payment method finish as a no-op in the workflow itself.+ let process_tracker_id =+ generate_task_id_for_network_tokenization_workflow(&payment_method_id, runner, task);++ let process_tracker_entry = storage::ProcessTrackerNew::new(+ process_tracker_id,+ task,+ runner,+ tag,+ tracking_data,+ None,+ common_utils::date_time::now(),+ common_enums::ApiVersion::V2,+ application_source,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to construct NETWORK_TOKENIZATION process tracker task")?;++ db.insert_process(process_tracker_entry)+ .await+ .map(|_| ())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Failed while inserting NETWORK_TOKENIZATION task to process_tracker for payment_method_id: {payment_method_id}"+ )+ })?;++ Ok(())+}++/// Schedules the async `NetworkTokenizationWorkflow` task for a payment method that was saved+/// without a network token.+///+/// Scheduling is best effort: the payment method create/update it belongs to has already been+/// committed by the time this runs, so a failure to enqueue is logged rather than propagated to+/// the caller.+#[cfg(feature = "v2")]+async fn schedule_network_tokenization_task(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ payment_method_id: &id_type::GlobalPaymentMethodId,+ customer_id: id_type::GlobalCustomerId,+) {+ let tracking_data = storage::NetworkTokenizationTrackingData {+ payment_method_id: payment_method_id.clone(),+ merchant_id: platform.get_provider().get_account().get_id().clone(),+ profile_id: profile.get_id().clone(),+ customer_id,+ };++ match add_network_tokenization_task(&*state.store, tracking_data, state.conf.application_source)+ .await+ {+ Ok(()) => logger::info!(+ payment_method_id=%payment_method_id.get_string_repr(),+ "Scheduled NetworkTokenizationWorkflow process tracker task"+ ),+ Err(err) => logger::error!(+ payment_method_id=%payment_method_id.get_string_repr(),+ ?err,+ "Failed to schedule NetworkTokenizationWorkflow process tracker task"+ ),+ }+}++/// Whether the async `NetworkTokenizationWorkflow` task should be scheduled for a payment method+/// that is being created or updated.+///+/// The network token columns on the payment method are expected to be empty at this point — the+/// token is generated by the scheduled job, not inline — so the profile-level setting, the+/// per-request opt-in and the payment method being a card are considered here.+#[cfg(feature = "v2")]+fn should_schedule_network_tokenization(+ profile: &domain::Profile,+ payment_method_type: common_enums::PaymentMethod,+ network_tokenization: Option<&common_types::payment_methods::NetworkTokenization>,+) -> bool {+ profile.is_network_tokenization_enabled+ && payment_method_type == common_enums::PaymentMethod::Card+ && network_tokenization+ .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable))+ .unwrap_or(false)+}+#[cfg(feature = "v2")]pub async fn add_payment_method_modular_backward_compat_task(db: &dyn StorageInterface,@@ -2719,26 +2845,20 @@ impl PaymentMethodResolver {.is_some()|| payment_method.network_token_locker_id.is_some()|| payment_method.network_token_payment_method_data.is_some();- let network_tokenization_resp = if req.network_tokenization.is_some()- && !payment_method_has_network_token_data- {- let customer_id = payment_method- .customer_id- .clone()- .get_required_value("GlobalCustomerId")?;- network_tokenize_and_vault_the_pmd(- state,- &source_payment_method_data,- platform,- req.network_tokenization.clone(),- profile.is_network_tokenization_enabled,- &customer_id,- )- .await- } else {- None- };+ // When the re-added card is not yet network tokenized, defer generation to the+ // async `NetworkTokenizationWorkflow` process tracker job (scheduled after the+ // update below) rather than tokenizing inline. The job needs a customer to+ // tokenize against, and it is not changed by this update, so it is read from the+ // existing payment method before it is consumed.+ let network_tokenization_customer_id = (!payment_method_has_network_token_data+ && should_schedule_network_tokenization(+ profile,+ req.payment_method_type,+ req.network_tokenization.as_ref(),+ ))+ .then(|| payment_method.customer_id.clone())+ .flatten();let mut update_payment_method_data: DomainPaymentMethodUpdate =(req, source_payment_method_data).into();@@ -2755,10 +2875,21 @@ impl PaymentMethodResolver {update_payment_method_data,&payment_method_id,Some(payment_method),- network_tokenization_resp,+ None,)).await?;+ if let Some(customer_id) = network_tokenization_customer_id {+ schedule_network_tokenization_task(+ state,+ platform,+ profile,+ &updated_payment_method.id,+ customer_id,+ )+ .await;+ }+Ok((response, updated_payment_method))}@@ -2852,15 +2983,14 @@ async fn execute_payment_method_create().await;- let network_tokenization_resp = network_tokenize_and_vault_the_pmd(- state,- &payment_method_data,- platform,- req.network_tokenization.clone(),- profile.is_network_tokenization_enabled,- customer_id,- )- .await;+ // Network tokenization is generated asynchronously via the `NetworkTokenizationWorkflow`+ // process tracker job (scheduled after the payment method row is created below), so the+ // payment method is initially persisted without network token data.+ let schedule_network_tokenization = should_schedule_network_tokenization(+ profile,+ req.payment_method_type,+ req.network_tokenization.as_ref(),+ );let (response, payment_method) = match vaulting_result {Ok((@@ -2880,7 +3010,7 @@ async fn execute_payment_method_create(&payment_method,None,None,- network_tokenization_resp.clone(),+ None,Some(req.payment_method_type),payment_method_subtype,external_vault_source,@@ -2963,6 +3093,17 @@ async fn execute_payment_method_create(}}?;+ if schedule_network_tokenization {+ schedule_network_tokenization_task(+ state,+ platform,+ profile,+ &payment_method.id,+ customer_id.clone(),+ )+ .await;+ }+Ok((response, payment_method))}@@ -3374,6 +3515,11 @@ pub struct BinEnriched<T> {pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,}+/// Generates a network token for the given card and vaults it.+///+/// Errors are returned to the caller so that callers which can act on a failure (such as the+/// async `NetworkTokenizationWorkflow`, which retries) are able to distinguish a failed+/// tokenization from one that was never applicable.#[cfg(feature = "v2")]pub async fn network_tokenize_and_vault_the_pmd(state: &SessionState,@@ -3382,71 +3528,183 @@ pub async fn network_tokenize_and_vault_the_pmd(network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,network_tokenization_enabled_for_profile: bool,customer_id: &id_type::GlobalCustomerId,-) -> Option<NetworkTokenPaymentMethodDetails> {- let network_token_pm_details_result: CustomResult<- NetworkTokenPaymentMethodDetails,- errors::NetworkTokenizationError,- > = async {- when(!network_tokenization_enabled_for_profile, || {- Err(report!(- errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile- ))- })?;+) -> CustomResult<NetworkTokenPaymentMethodDetails, errors::NetworkTokenizationError> {+ when(!network_tokenization_enabled_for_profile, || {+ Err(report!(+ errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile+ ))+ })?;- let is_network_tokenization_enabled_for_pm = network_tokenization- .as_ref()- .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable))- .unwrap_or(false);-- let card_data = payment_method_data- .get_card()- .and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card))- .ok_or_else(|| {- report!(errors::NetworkTokenizationError::NotSupported {- message: "Payment method".to_string(),- })- })?;+ let is_network_tokenization_enabled_for_pm = network_tokenization+ .as_ref()+ .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable))+ .unwrap_or(false);++ let card_data = payment_method_data+ .get_card()+ .and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card))+ .ok_or_else(|| {+ report!(errors::NetworkTokenizationError::NotSupported {+ message: "Payment method".to_string(),+ })+ })?;- let (resp, network_token_req_ref_id) =- network_tokenization::make_card_network_tokenization_request(- state,- card_data,- customer_id,- )+ let (resp, network_token_req_ref_id) =+ network_tokenization::make_card_network_tokenization_request(state, card_data, customer_id).await?;- let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp);- let vaulting_resp = vault::add_payment_method_to_vault(- state,- platform,- &network_token_vaulting_data,- None,- customer_id,- Some(pm_types::WriteMode::Insert), // Insert mode for new network tokens- )- .await- .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)- .attach_printable("Failed to vault network token")?;+ let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp);+ let vaulting_resp = vault::add_payment_method_to_vault(+ state,+ platform,+ &network_token_vaulting_data,+ None,+ customer_id,+ Some(pm_types::WriteMode::Insert), // Insert mode for new network tokens+ )+ .await+ .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)+ .attach_printable("Failed to vault network token")?;- let key_manager_state = &(state).into();- let network_token_pmd = core_utils::create_encrypted_data(- key_manager_state,- platform.get_provider().get_key_store(),- network_token_vaulting_data.get_payment_methods_data(),- common_utils::type_name!(diesel_models::payment_method::PaymentMethod),- )- .await- .change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed)- .attach_printable("Failed to encrypt PaymentMethodsData")?;+ let key_manager_state = &(state).into();+ let network_token_pmd = core_utils::create_encrypted_data(+ key_manager_state,+ platform.get_provider().get_key_store(),+ network_token_vaulting_data.get_payment_methods_data(),+ common_utils::type_name!(diesel_models::payment_method::PaymentMethod),+ )+ .await+ .change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed)+ .attach_printable("Failed to encrypt PaymentMethodsData")?;- Ok(NetworkTokenPaymentMethodDetails {- network_token_requestor_reference_id: network_token_req_ref_id,- network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(),- network_token_pmd,- })- }+ Ok(NetworkTokenPaymentMethodDetails {+ network_token_requestor_reference_id: network_token_req_ref_id,+ network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(),+ network_token_pmd,+ })+}++/// Called from the `NetworkTokenizationWorkflow` process tracker job (v2).+///+/// Re-fetches the card from the vault for the given payment method, generates a network token+/// and persists the network token details on the payment method row. This is the async+/// counterpart of the synchronous network tokenization performed during payment method create+/// and update.+///+/// A failure is returned as an error so that the workflow can retry it. Payment methods that+/// network tokenization does not apply to at all are reported as+/// [`NetworkTokenGenerationOutcome::NotApplicable`], since retrying those cannot succeed.+#[cfg(feature = "v2")]+pub async fn generate_network_token_for_payment_method(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ payment_method: domain::PaymentMethod,+) -> RouterResult<NetworkTokenGenerationOutcome> {+ let db = &*state.store;++ let customer_id = payment_method+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;++ // Re-fetch the card that was vaulted at create/update time.+ let vault_data = Box::pin(vault::retrieve_payment_method_from_vault(+ state,+ platform,+ profile,+ &payment_method,+ ))+ .await+ .attach_printable("Failed to retrieve payment method from vault for network tokenization")?+ .data;++ // The per-payment-method opt-in was recorded when the task was scheduled and is not persisted+ // on the payment method, so request tokenization with the toggle enabled here. The+ // profile-level flag is still passed through and re-checked by the callee.+ let network_tokenization_resp = network_tokenize_and_vault_the_pmd(+ state,+ &vault_data,+ platform,+ Some(common_types::payment_methods::NetworkTokenization {+ enable: common_enums::NetworkTokenizationToggle::Enable,+ }),+ profile.is_network_tokenization_enabled,+ &customer_id,+ ).await;- network_token_pm_details_result.ok()++ match network_tokenization_resp {+ Ok(network_token) => {+ // v2 has no NT-only update variant; `GenericUpdate` is the one that carries the+ // network token columns. Its changeset skips `None` fields, so only the network token+ // columns (and last_modified) are written.+ let pm_update = storage::PaymentMethodUpdate::GenericUpdate {+ payment_method_data: None,+ status: None,+ locker_id: None,+ payment_method_type_v2: None,+ payment_method_subtype: None,+ network_token_requestor_reference_id: Some(+ network_token.network_token_requestor_reference_id,+ ),+ network_token_locker_id: Some(network_token.network_token_locker_id),+ network_token_payment_method_data: Some(network_token.network_token_pmd.into()),+ locker_fingerprint_id: None,+ connector_mandate_details: Box::new(None),+ external_vault_source: None,+ network_transaction_id: None,+ network_transaction_link_id: None,+ last_modified_by: platform+ .get_initiator()+ .and_then(|initiator| initiator.to_created_by())+ .map(|last_modified_by| last_modified_by.to_string()),+ };++ db.update_payment_method(+ platform.get_provider().get_key_store(),+ payment_method,+ pm_update,+ platform.get_provider().get_account().storage_scheme,+ None,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update payment method with network token details")+ .map(|_| NetworkTokenGenerationOutcome::Generated)+ }++ // Neither of these can be fixed by running the task again, so report them as a terminal+ // outcome instead of an error that burns the retry budget.+ Err(err)+ if matches!(+ err.current_context(),+ errors::NetworkTokenizationError::NotSupported { .. }+ | errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile+ ) =>+ {+ logger::warn!(+ payment_method_id=%payment_method.id.get_string_repr(),+ ?err,+ "Network tokenization is not applicable for this payment method, not retrying"+ );+ Ok(NetworkTokenGenerationOutcome::NotApplicable)+ }++ Err(err) => Err(err)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to generate and vault the network token"),+ }+}++/// Terminal outcome of an async network token generation attempt.+#[cfg(feature = "v2")]+#[derive(Clone, Copy, Debug)]+pub enum NetworkTokenGenerationOutcome {+ /// A network token was generated and persisted on the payment method.+ Generated,+ /// Network tokenization does not apply to this payment method; retrying cannot help.+ NotApplicable,}#[cfg(feature = "v2")]@@ -6067,6 +6325,10 @@ pub async fn update_payment_method()).await?;+ // Network tokenization is intentionally not scheduled here: the update request carries no+ // network tokenization opt-in field, so there is no per-payment-method consent to act on.+ // Scheduling happens only in the create flow, where the request opts in explicitly.+Ok(services::ApplicationResponse::Json(response))}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex efe531d90b..604b903c5f 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3179,7 +3179,7 @@ wherelet jwekey = state.conf.jwekey.get_inner();let response_type_name = type_name!(T);- let response = services::call_connector_api(state, request, flow_name)+ let response = services::call_connector_api(state, request, flow_name, None).await.change_context(errors::VaultError::ApiError)?;diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rsindex 1c655d755e..e4ed3060b3 100644--- a/crates/router/src/core/payment_methods/network_tokenization.rs+++ b/crates/router/src/core/payment_methods/network_tokenization.rs@@ -87,6 +87,7 @@ async fn call_network_token_service(url: &str,body: Option<RequestContent>,operation_tag: &str,+ option_timeout_secs: Option<u64>,) -> CustomResult<Result<Response, Response>, errors::NetworkTokenizationError> {let mut request = services::Request::new(method, url);request.add_header(headers::CONTENT_TYPE, "application/json".into());@@ -110,7 +111,7 @@ async fn call_network_token_service(request);- services::call_connector_api(state, request, operation_tag)+ services::call_connector_api(state, request, operation_tag, option_timeout_secs).await.change_context(errors::NetworkTokenizationError::ApiError)}@@ -164,6 +165,7 @@ pub async fn mk_tokenization_req(tokenization_service.generate_token_url.as_str(),Some(RequestContent::Json(Box::new(api_payload))),"generate_token",+ None,).await;@@ -244,6 +246,7 @@ pub async fn make_nt_eligibility_call(&url_string,None,"fetch_nt_eligibility",+ None,).await;@@ -334,6 +337,7 @@ pub async fn generate_network_token(tokenization_service.generate_token_url.as_str(),Some(RequestContent::Json(Box::new(api_payload))),"generate_token",+ None,).await;@@ -515,6 +519,12 @@ pub async fn get_network_token(.unwrap_or(serde_json::json!({ "error": "failed to mask serialize"}));logger::info!(raw_network_token_service_request=?masked_request_body);+ // Bound the fetch so a slow tokenization service does not block the payment; on timeout the+ // caller falls back to the card details from the locker. The budget is resolved from+ // superposition (`network_token_fetch_timeout_in_secs`) with database fallback.+ let fetch_timeout_in_secs =+ payment_methods::utils::get_network_token_fetch_timeout_in_secs(state).await;+let response = call_network_token_service(state,tokenization_service,@@ -522,6 +532,7 @@ pub async fn get_network_token(tokenization_service.fetch_token_url.as_str(),Some(RequestContent::Json(Box::new(payload))),"get_network_token",+ Some(fetch_timeout_in_secs),).await;@@ -582,6 +593,7 @@ pub async fn get_network_token(tokenization_service.fetch_token_url.as_str(),Some(RequestContent::Json(Box::new(payload))),"get_network_token",+ None,).await;@@ -623,34 +635,35 @@ pub async fn get_token_from_tokenization_service(network_token_requestor_ref_id: String,pm_data: &domain::PaymentMethod,) -> errors::RouterResult<domain::NetworkTokenData> {- let token_response =- if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {- record_operation_time(+ let token_response = if let Some(network_tokenization_service) =+ &state.conf.network_tokenization_service+ {+ Box::pin(record_operation_time(async {get_network_token(- state,- pm_data.customer_id.clone().get_required_value("customer_id")?,- network_token_requestor_ref_id,- network_tokenization_service.get_inner(),- )- .await- .inspect_err(- |e| logger::error!(error=?e, "Error while fetching token from tokenization service")- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Fetch network token failed")+ state,+ pm_data.customer_id.clone().get_required_value("customer_id")?,+ network_token_requestor_ref_id,+ network_tokenization_service.get_inner(),+ )+ .await+ .inspect_err(|e| {+ logger::error!(error=?e, "Error while fetching token from tokenization service")+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Fetch network token failed")},&metrics::FETCH_NETWORK_TOKEN_TIME,&[],- )+ )).await- } else {- Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)- .inspect_err(|err| {- logger::error!(error=? err);- })- .change_context(errors::ApiErrorResponse::InternalServerError)- }?;+ } else {+ Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)+ .inspect_err(|err| {+ logger::error!(error=? err);+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ }?;let token_decrypted = pm_data.network_token_payment_method_data@@ -860,6 +873,7 @@ pub async fn check_token_status_with_tokenization_service(tokenization_service.check_token_status_url.as_str(),Some(RequestContent::Json(Box::new(payload))),"check_token_status",+ None,).await;let res = response@@ -927,6 +941,7 @@ pub async fn check_token_status_with_tokenization_service(tokenization_service.check_token_status_url.as_str(),Some(RequestContent::Json(Box::new(payload))),"check_token_status",+ None,).await;let res = response@@ -1086,6 +1101,7 @@ pub async fn delete_network_token_from_tokenization_service(tokenization_service.delete_token_url.as_str(),Some(RequestContent::Json(Box::new(payload))),"delete_network_token",+ None,).await;let res = response@@ -1186,6 +1202,7 @@ pub async fn fetch_altid_and_cryptogram(tokenization_service.fetch_altid_url.as_str(),Some(RequestContent::Json(Box::new(payload))),"fetch_altid",+ None,).await;diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 8cb40b960a..0a4b533980 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -884,6 +884,23 @@ pub async fn get_should_trigger_backwards_compatibility_inline(.await}+/// Timeout (in seconds) for fetching a network token from the tokenization service during a+/// payment, resolved from superposition with database fallback (global key+/// `network_token_fetch_timeout_in_secs`, default 4).+pub async fn get_network_token_fetch_timeout_in_secs(state: &SessionState) -> u64 {+ let dimensions = dimension_state::Dimensions::new();++ let timeout_in_secs = dimensions+ .get_network_token_fetch_timeout_in_secs(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await;++ u64::from(timeout_in_secs)+}+pub async fn get_should_trigger_fingerprint_migration(state: &SessionState,customer_id: Option<&common_utils::id_type::CustomerId>,diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 82e1e24651..3883199faf 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -2017,7 +2017,7 @@ pub async fn call_to_vault<V: pm_types::VaultingInterface>(Some(additional_headers),).await?;- let response = services::call_connector_api(state, request, V::get_vaulting_flow_name())+ let response = services::call_connector_api(state, request, V::get_vaulting_flow_name(), None).await.change_context(errors::VaultError::VaultAPIError);diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 384b43b476..0b1b2af775 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -1042,7 +1042,7 @@ where};let (merchant_connector_account, router_data, tokenization_action) =- call_connector_service_prerequisites(+ Box::pin(call_connector_service_prerequisites(state,platform,connector.connector_data.clone(),@@ -1053,7 +1053,7 @@ wherefalse,None,&feature_config,- )+ )).await?;let (updated_customer, call_connector_service_response, updated_state) =@@ -1229,7 +1229,7 @@ where};let (merchant_connector_account, router_data, tokenization_action) =- call_connector_service_prerequisites(+ Box::pin(call_connector_service_prerequisites(state,platform,connector_data.clone(),@@ -1240,7 +1240,7 @@ wherefalse,routing_decision,&feature_config,- )+ )).await?;let (updated_customer, call_connector_service_response, updated_state) =@@ -5965,9 +5965,12 @@ whereif let (Some(domain::PaymentMethodData::Card(card_data)), Some(customer_id)) =(payment_method_data, customer_id){- let vault_operation =- get_vault_operation_for_pre_network_tokenization(state, customer_id, card_data)- .await;+ let vault_operation = Box::pin(get_vault_operation_for_pre_network_tokenization(+ state,+ customer_id,+ card_data,+ ))+ .await;match vault_operation {payments::VaultOperation::SaveCardAndNetworkTokenData(card_and_network_token_data,@@ -11046,10 +11049,13 @@ pub async fn get_vault_operation_for_pre_network_tokenization(customer_id: id_type::CustomerId,card_data: &hyperswitch_domain_models::payment_method_data::Card,) -> payments::VaultOperation {- let pre_tokenization_response =- tokenization::pre_payment_tokenization(state, customer_id, card_data)- .await- .ok();+ let pre_tokenization_response = Box::pin(tokenization::pre_payment_tokenization(+ state,+ customer_id,+ card_data,+ ))+ .await+ .ok();match pre_tokenization_response {Some((Some(token_response), Some(token_ref))) => {let token_data = domain::NetworkTokenData::from(token_response);diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex 408fe8336b..e0d810b6f4 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -537,6 +537,7 @@ async fn create_applepay_session_token(state,applepay_session_request,"create_apple_pay_session_token",+ None,).await;@@ -566,6 +567,7 @@ async fn create_applepay_session_token(state,applepay_retry_session_request,"create_apple_pay_session_token",+ None,).await}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 8a7211564e..80c253b714 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2919,11 +2919,11 @@ pub async fn retrieve_payment_method_data_with_permanent_token(network_token_requestor_ref_id,) => {logger::info!("Fetching network token data from tokenization service");- match network_tokenization::get_token_from_tokenization_service(+ match Box::pin(network_tokenization::get_token_from_tokenization_service(state,network_token_requestor_ref_id,&payment_method_info,- )+ )).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("failed to fetch network token data from tokenization service")diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex 2a5c2a33b6..8ae786842d 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -2,6 +2,7 @@ use api_models::{enums::FrmSuggestion, payments::PaymentsConfirmIntentRequest};use async_trait::async_trait;use common_utils::{ext_traits::Encode, fp_utils::when, id_type, types::keymanager::ToEncryptable};use error_stack::ResultExt;+use futures::FutureExt;use hyperswitch_domain_models::{mandates, payments::PaymentConfirmData};use hyperswitch_interfaces::api::ConnectorSpecifications;use hyperswitch_masking::{ExposeOptionInterface, PeekInterface};@@ -561,18 +562,18 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfSome(domain::payment_method_data::PaymentMethodData::CardToken(card_token)),None,) => {- let (payment_method, vault_data) = Box::pin(+ let (payment_method, vault_data) =payment_methods::vault::retrieve_payment_method_from_vault_using_payment_token(state,platform,business_profile,payment_token,&payment_data.payment_attempt.payment_method_type,- ),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to retrieve payment method from vault")?;+ )+ .boxed()+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve payment method from vault")?;let (card_cvc, card_holder_name) = {(@@ -588,6 +589,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf&payment_method.get_id().get_string_repr().to_string(),platform.get_processor().get_key_store(),)+ .boxed().await,).attach_printable("card_cvc not provided")?,@@ -646,15 +648,15 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfstorage_type: common_enums::StorageType::Persistent, //since customer acceptance is present, we always store it persistently};- let (_pm_response, payment_method) =- Box::pin(payment_methods::create_payment_method_core(- state,- &state.get_req_state(),- req,- platform,- business_profile,- ))- .await?;+ let (_pm_response, payment_method) = payment_methods::create_payment_method_core(+ state,+ &state.get_req_state(),+ req,+ platform,+ business_profile,+ )+ .boxed()+ .await?;// Don't modify payment_method_data in this case, only the payment_method and payment_method_id(Some(payment_method), None)diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rsindex 690cc8cb83..3b715a1878 100644--- a/crates/router/src/core/payments/retry.rs+++ b/crates/router/src/core/payments/retry.rs@@ -410,7 +410,7 @@ where.await?;let (merchant_connector_account, router_data, tokenization_action) =- payments::call_connector_service_prerequisites(+ Box::pin(payments::call_connector_service_prerequisites(state,platform,connector.clone(),@@ -421,7 +421,7 @@ whereshould_retry_with_pan,routing_decision,feature_config,- )+ )).await?;let connector_customer_map = customerdiff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rsindex aea7b6841e..f00217bc6c 100644--- a/crates/router/src/core/payments/routing/utils.rs+++ b/crates/router/src/core/payments/routing/utils.rs@@ -222,7 +222,7 @@ wherelet closure = || async {let request_start = std::time::Instant::now();let response =- services::call_connector_api(state, http_request, "Decision Engine API call")+ services::call_connector_api(state, http_request, "Decision Engine API call", None).await.change_context(errors::RoutingError::OpenRouterCallFailed)?;diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 1f18739f19..e13715227e 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -326,17 +326,19 @@ where.get_payment_method_data().get_card_data().and_then(|card| card.card_network.clone());- // Payment method that was saved without a network token, and therefore still needs- // one to be generated asynchronously by the process tracker.- let mut payment_method_pending_network_tokenization: Option<String> = None;-- let pm_id = if let Some(existing_pm) = payment_method_info.clone().filter(|_| {- matches!(- save_payment_method_data.request.get_payment_method_data(),- domain::PaymentMethodData::MandatePayment- | domain::PaymentMethodData::CardToken(_)- )- }) {++ // `payment_method_pending_network_tokenization` carries the id of a payment method+ // that may still need a network token generated asynchronously by the process+ // tracker. It is produced alongside `pm_id` by the branches below instead of being+ // assigned to a mutable variable.+ let (pm_id, payment_method_pending_network_tokenization) = if let Some(existing_pm) =+ payment_method_info.clone().filter(|_| {+ matches!(+ save_payment_method_data.request.get_payment_method_data(),+ domain::PaymentMethodData::MandatePayment+ | domain::PaymentMethodData::CardToken(_)+ )+ }) {// Recharge of an already-saved payment method where the request// carries no fresh raw card data — either a recurring/MIT charge via// an established connector mandate (PaymentMethodData::MandatePayment)@@ -359,7 +361,11 @@ wherelogger::error!("Failed to update last used at: {:?}", e);}).ok();- Some(existing_pm.get_id().clone())++ // The existing payment method may still be missing a network token (the workflow+ // skips it if one is already present), so hand it to the process tracker as well.+ let existing_pm_id = existing_pm.get_id().clone();+ (Some(existing_pm_id.clone()), Some(existing_pm_id))} else if customer_acceptance.is_some() {let payment_method_data =save_payment_method_data.request.get_payment_method_data();@@ -1095,24 +1101,14 @@ where// network or a failed tokenization service call. In every such case, defer// generation to the process tracker. The workflow skips payment methods that are// already tokenized, so this is safe for duplicated cards as well.- if save_payment_method_data.payment_method == PaymentMethod::Card- && !network_token_generated- {- payment_method_pending_network_tokenization =- Some(resp.payment_method_id.clone());- }+ let pending_network_tokenization = (save_payment_method_data.payment_method+ == PaymentMethod::Card+ && !network_token_generated)+ .then(|| resp.payment_method_id.clone());- Some(resp.payment_method_id)+ (Some(resp.payment_method_id), pending_network_tokenization)} else {- // No customer acceptance was provided in this transaction, so no new payment- // method is created. But the payment method may already have been saved earlier- // (e.g. recurring / MIT flow reusing a stored card). If that saved payment method- // still lacks a network token, defer generation to the process tracker.- payment_method_pending_network_tokenization = payment_method_info- .as_ref()- .filter(|pm_info| pm_info.network_token_requestor_reference_id.is_none())- .map(|pm_info| pm_info.payment_method_id.clone());- None+ (None, None)};// If network tokenization is enabled for the profile, trigger the process tracker@@ -1123,7 +1119,7 @@ wherepayment_method_pending_network_tokenization,customer_id_for_network_tokenization,) {- payment_methods::add_network_tokenization_task(+ let scheduling_result = payment_methods::add_network_tokenization_task(db,types::storage::NetworkTokenizationTrackingData {payment_method_id: pending_pm_id.clone(),@@ -1137,22 +1133,21 @@ where},state.conf.application_source,)- .await- .map_or_else(- |err| {- logger::error!(- payment_method_id=%pending_pm_id,- ?err,- "Failed to schedule NetworkTokenizationWorkflow process tracker task"- );- },- |()| {- logger::info!(- payment_method_id=%pending_pm_id,- "Scheduled NetworkTokenizationWorkflow process tracker task"- );- },- );+ .await;++ // Scheduling is best effort: the payment method has already been saved, so a+ // failure to enqueue is logged rather than failing the payment.+ match scheduling_result {+ Ok(()) => logger::info!(+ payment_method_id=%pending_pm_id,+ "Scheduled NetworkTokenizationWorkflow process tracker task"+ ),+ Err(err) => logger::error!(+ payment_method_id=%pending_pm_id,+ ?err,+ "Failed to schedule NetworkTokenizationWorkflow process tracker task"+ ),+ }}}// check if there needs to be a config if yes then remove it to a different place@@ -1249,7 +1244,7 @@ pub async fn pre_payment_tokenization(network_tokenization_service,) {(Some(token_ref), Some(network_tokenization_service)) => {- let network_token = record_operation_time(+ let network_token = Box::pin(record_operation_time(async {network_tokenization::get_network_token(state,@@ -1261,7 +1256,7 @@ pub async fn pre_payment_tokenization(},&metrics::FETCH_NETWORK_TOKEN_TIME,&[],- )+ )).await;match network_token {Ok(token_response) => {@@ -1668,7 +1663,7 @@ pub async fn save_network_token_in_locker(// empty CVC. Send no card security code at all in that case, rather than an// empty one.let optional_card_cvc =- Some(card_data.card_cvc.clone()).filter(|cvc| !cvc.peek().is_empty());+ (!card_data.card_cvc.peek().is_empty()).then(|| card_data.card_cvc.clone());match network_tokenization::make_card_network_tokenization_request(state,&domain::CardDetail::from(card_data),diff --git a/crates/router/src/core/proxy.rs b/crates/router/src/core/proxy.rsindex 9ff419932c..fcc2ffc9a2 100644--- a/crates/router/src/core/proxy.rs+++ b/crates/router/src/core/proxy.rs@@ -92,7 +92,7 @@ async fn execute_proxy_request(.set_body(request::RequestContent::Json(Box::new(processed_body))).build();- let response = services::call_connector_api(state, request, "proxy")+ let response = services::call_connector_api(state, request, "proxy", None).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to call the destination");diff --git a/crates/router/src/core/relay.rs b/crates/router/src/core/relay.rsindex ce6f326458..58135de35d 100644--- a/crates/router/src/core/relay.rs+++ b/crates/router/src/core/relay.rs@@ -1111,7 +1111,7 @@ async fn process_unreferenced_refund(.attach_printable("Failed to build relay request")?;let api_response =- call_connector_api(state, connector_request, "relay_unreferenced_refund").await;+ call_connector_api(state, connector_request, "relay_unreferenced_refund", None).await;let (response_bytes, relay_update) = match api_response {Ok(resp) => {diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rsindex 47a8634e4d..46b7b8ac36 100644--- a/crates/router/src/core/verification.rs+++ b/crates/router/src/core/verification.rs@@ -49,6 +49,7 @@ pub async fn verify_merchant_creds_for_applepay(&state,apple_pay_merch_verification_req,"verify_merchant_creds_for_applepay",+ None,).await;utils::log_applepay_verification_response_if_error(&response);diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rsindex 1190ee4eef..cd3ec01509 100644--- a/crates/router/src/services/pm_auth.rs+++ b/crates/router/src/services/pm_auth.rs@@ -33,6 +33,7 @@ wherestate,request,"execute_connector_processing_step",+ None,).await;logger::debug!(connector_response=?response);diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rsindex 12589e5e86..353e4f2f02 100644--- a/crates/router/src/types/api/verify_connector.rs+++ b/crates/router/src/types/api/verify_connector.rs@@ -172,10 +172,14 @@ pub trait VerifyConnector {})?.ok_or(errors::ApiErrorResponse::InternalServerError)?;- let response =- services::call_connector_api(&state.to_owned(), request, "verify_connector_request")- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let response = services::call_connector_api(+ &state.to_owned(),+ request,+ "verify_connector_request",+ None,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;match response {Ok(_) => Ok(services::ApplicationResponse::StatusOk),diff --git a/crates/router/src/types/api/verify_connector/paypal.rs b/crates/router/src/types/api/verify_connector/paypal.rsindex d7c4fca748..bd68c12a11 100644--- a/crates/router/src/types/api/verify_connector/paypal.rs+++ b/crates/router/src/types/api/verify_connector/paypal.rs@@ -28,9 +28,10 @@ impl VerifyConnector for connector::Paypal {})?.ok_or(errors::ApiErrorResponse::InternalServerError)?;- let response = services::call_connector_api(&state.to_owned(), request, "get_access_token")- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let response =+ services::call_connector_api(&state.to_owned(), request, "get_access_token", None)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;match response {Ok(res) => Some(diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rsindex e8b2e00ee3..bcdacde2a5 100644--- a/crates/router/src/types/storage/payment_method.rs+++ b/crates/router/src/types/storage/payment_method.rs@@ -259,3 +259,14 @@ pub struct NetworkTokenizationTrackingData {/// always be fetched from the locker instead.pub card_network: Option<common_enums::CardNetwork>,}++#[cfg(feature = "v2")]+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]+pub struct NetworkTokenizationTrackingData {+ pub payment_method_id: common_utils::id_type::GlobalPaymentMethodId,+ pub merchant_id: common_utils::id_type::MerchantId,+ /// Profile the payment method was created against. Network tokenization is configured per+ /// profile, so this is used to look up the profile in the async workflow.+ pub profile_id: common_utils::id_type::ProfileId,+ pub customer_id: common_utils::id_type::GlobalCustomerId,+}diff --git a/crates/router/src/workflows/network_tokenization.rs b/crates/router/src/workflows/network_tokenization.rsindex 750e8455af..7daf746c3d 100644--- a/crates/router/src/workflows/network_tokenization.rs+++ b/crates/router/src/workflows/network_tokenization.rs@@ -1,161 +1,351 @@-#[cfg(feature = "v1")]use common_utils::ext_traits::ValueExt;-use scheduler::workflows::ProcessTrackerWorkflow;+use error_stack::Report;+use scheduler::{+ consumer::{self, types::process_data},+ utils as pt_utils,+ workflows::ProcessTrackerWorkflow,+};++#[cfg(feature = "v2")]+use crate::core::payment_methods;#[cfg(feature = "v1")]-use scheduler::{consumer::types::process_data, utils as pt_utils};+use crate::core::payments::tokenization;+use crate::{+ errors, logger,+ routes::SessionState,+ types::{domain, storage, storage::NetworkTokenizationTrackingData},+};-use crate::{errors, logger, routes::SessionState, types::storage};+const NETWORK_TOKENIZATION_DISABLED_STATUS: &str = "SKIPPED_NT_DISABLED";+const ALREADY_TOKENIZED_STATUS: &str = "ALREADY_TOKENIZED";+const COMPLETED_BY_PT_STATUS: &str = "COMPLETED_BY_PT";+const RETRIES_EXCEEDED_STATUS: &str = "RETRIES_EXCEEDED";+#[cfg(feature = "v2")]+const NOT_APPLICABLE_STATUS: &str = "SKIPPED_NT_NOT_APPLICABLE";++/// Result of one run of the workflow, before it is recorded on the process tracker entry.+enum TaskOutcome {+ /// Nothing left to do: finish the task with this business status.+ Finished(&'static str),+ /// The attempt failed and is worth retrying while the retry budget lasts.+ Failed(Report<errors::ApiErrorResponse>),+}pub struct NetworkTokenizationWorkflow;#[async_trait::async_trait]impl ProcessTrackerWorkflow<SessionState> for NetworkTokenizationWorkflow {- #[cfg(feature = "v1")]async fn execute_workflow<'a>(&'a self,state: &'a SessionState,process: storage::ProcessTracker,) -> Result<(), errors::ProcessTrackerError> {- use crate::{- core::payments::tokenization, types::storage::NetworkTokenizationTrackingData,- };-- let db = &*state.store;-let tracking_data: NetworkTokenizationTrackingData = process.tracking_data.clone().parse_value("NetworkTokenizationTrackingData")?;- let retry_count = process.retry_count;- let merchant_id = tracking_data.merchant_id.clone();+ let payment_method_id = get_payment_method_id(&tracking_data);- let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )- .await?;+ let outcome = Box::pin(generate_network_token(state, &tracking_data)).await?;++ finish_task(state, process, &payment_method_id, outcome).await+ }++ async fn error_handler<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ error: errors::ProcessTrackerError,+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {+ consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await+ }+}++#[cfg(feature = "v1")]+fn get_payment_method_id(tracking_data: &NetworkTokenizationTrackingData) -> String {+ tracking_data.payment_method_id.clone()+}- let merchant_account = db- .find_merchant_account_by_merchant_id(&merchant_id, &key_store)- .await?;+#[cfg(feature = "v2")]+fn get_payment_method_id(tracking_data: &NetworkTokenizationTrackingData) -> String {+ tracking_data.payment_method_id.get_string_repr().to_owned()+}++/// Generates and persists the network token for the payment method the task was scheduled for.+///+/// Errors that the task can recover from by running again are returned as+/// [`TaskOutcome::Failed`]; errors in reading the merchant, profile or payment method are+/// propagated, since they leave the task in an unknown state.+#[cfg(feature = "v1")]+async fn generate_network_token(+ state: &SessionState,+ tracking_data: &NetworkTokenizationTrackingData,+) -> Result<TaskOutcome, errors::ProcessTrackerError> {+ let db = &*state.store;+ let merchant_id = tracking_data.merchant_id.clone();++ let key_store = db+ .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ .await+ .inspect_err(|error| {+ logger::error!(+ merchant_id=%merchant_id.get_string_repr(),+ ?error,+ "Failed to fetch merchant key store for network tokenization workflow"+ );+ })?;- let business_profile = db- .find_business_profile_by_merchant_id_profile_id(+ let merchant_account = db+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)+ .await+ .inspect_err(|error| {+ logger::error!(+ merchant_id=%merchant_id.get_string_repr(),+ ?error,+ "Failed to fetch merchant account for network tokenization workflow"+ );+ })?;++ let business_profile = db+ .find_business_profile_by_merchant_id_profile_id(+ &key_store,+ &merchant_id,+ &tracking_data.profile_id,+ )+ .await+ .inspect_err(|error| {+ logger::error!(+ merchant_id=%merchant_id.get_string_repr(),+ profile_id=%tracking_data.profile_id.get_string_repr(),+ ?error,+ "Failed to fetch business profile for network tokenization workflow"+ );+ })?;++ if !business_profile.is_network_tokenization_enabled {+ // A skip is a terminal success, not a failure, so finish with a business status rather+ // than mapping it to an error state (which would trigger retries).+ logger::info!(+ payment_method_id=%tracking_data.payment_method_id,+ "Network tokenization is disabled for this profile, skipping"+ );+ Ok(TaskOutcome::Finished(NETWORK_TOKENIZATION_DISABLED_STATUS))+ } else {+ let payment_method = db+ .find_payment_method(&key_store,- &merchant_id,- &tracking_data.profile_id,+ &tracking_data.payment_method_id,+ merchant_account.storage_scheme,)- .await?;+ .await+ .inspect_err(|error| {+ logger::error!(+ payment_method_id=%get_payment_method_id(tracking_data),+ ?error,+ "Failed to fetch payment method for network tokenization workflow"+ );+ })?;- if !business_profile.is_network_tokenization_enabled {+ if payment_method+ .network_token_requestor_reference_id+ .is_some()+ {+ // Already tokenized — another terminal success, no retry needed.logger::info!(payment_method_id=%tracking_data.payment_method_id,- "Network tokenization is disabled for this profile, skipping"+ "Payment method already has a network token, skipping"+ );+ Ok(TaskOutcome::Finished(ALREADY_TOKENIZED_STATUS))+ } else {+ let platform = domain::Platform::new(+ merchant_account.clone(),+ key_store.clone(),+ merchant_account,+ key_store,+ None,);- return db- .as_scheduler()- .finish_process_with_business_status(process, "SKIPPED_NT_DISABLED")- .await- .map_err(Into::<errors::ProcessTrackerError>::into);++ let result = Box::pin(tokenization::generate_network_token_for_payment_method(+ state,+ &platform,+ tracking_data,+ payment_method,+ ))+ .await;++ Ok(match result {+ Ok(()) => TaskOutcome::Finished(COMPLETED_BY_PT_STATUS),+ Err(err) => TaskOutcome::Failed(err),+ })}+ }+}++/// Generates and persists the network token for the payment method the task was scheduled for.+///+/// Errors that the task can recover from by running again are returned as+/// [`TaskOutcome::Failed`]; errors in reading the merchant, profile or payment method are+/// propagated, since they leave the task in an unknown state.+#[cfg(feature = "v2")]+async fn generate_network_token(+ state: &SessionState,+ tracking_data: &NetworkTokenizationTrackingData,+) -> Result<TaskOutcome, errors::ProcessTrackerError> {+ let db = &*state.store;+ let merchant_id = tracking_data.merchant_id.clone();++ let key_store = db+ .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ .await+ .inspect_err(|error| {+ logger::error!(+ merchant_id=%merchant_id.get_string_repr(),+ ?error,+ "Failed to fetch merchant key store for network tokenization workflow"+ );+ })?;++ let merchant_account = db+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)+ .await+ .inspect_err(|error| {+ logger::error!(+ merchant_id=%merchant_id.get_string_repr(),+ ?error,+ "Failed to fetch merchant account for network tokenization workflow"+ );+ })?;++ let business_profile = db+ .find_business_profile_by_merchant_id_profile_id(+ &key_store,+ &merchant_id,+ &tracking_data.profile_id,+ )+ .await+ .inspect_err(|error| {+ logger::error!(+ merchant_id=%merchant_id.get_string_repr(),+ profile_id=%tracking_data.profile_id.get_string_repr(),+ ?error,+ "Failed to fetch business profile for network tokenization workflow"+ );+ })?;+ if !business_profile.is_network_tokenization_enabled {+ // A skip is a terminal success, not a failure, so finish with a business status rather+ // than mapping it to an error state (which would trigger retries).+ logger::info!(+ payment_method_id=%tracking_data.payment_method_id.get_string_repr(),+ "Network tokenization is disabled for this profile, skipping"+ );+ Ok(TaskOutcome::Finished(NETWORK_TOKENIZATION_DISABLED_STATUS))+ } else {let payment_method = db.find_payment_method(&key_store,&tracking_data.payment_method_id,merchant_account.storage_scheme,)- .await?;+ .await+ .inspect_err(|error| {+ logger::error!(+ payment_method_id=%get_payment_method_id(tracking_data),+ ?error,+ "Failed to fetch payment method for network tokenization workflow"+ );+ })?;- // Skip if already tokenizedif payment_method.network_token_requestor_reference_id.is_some(){+ // Already tokenized — another terminal success, no retry needed.logger::info!(- payment_method_id=%tracking_data.payment_method_id,+ payment_method_id=%tracking_data.payment_method_id.get_string_repr(),"Payment method already has a network token, skipping");- return db- .as_scheduler()- .finish_process_with_business_status(process, "ALREADY_TOKENIZED")- .await- .map_err(Into::<errors::ProcessTrackerError>::into);+ Ok(TaskOutcome::Finished(ALREADY_TOKENIZED_STATUS))+ } else {+ let platform = domain::Platform::new(+ merchant_account.clone(),+ key_store.clone(),+ merchant_account,+ key_store,+ None,+ );++ let result = Box::pin(payment_methods::generate_network_token_for_payment_method(+ state,+ &platform,+ &business_profile,+ payment_method,+ ))+ .await;++ Ok(match result {+ Ok(payment_methods::NetworkTokenGenerationOutcome::Generated) => {+ TaskOutcome::Finished(COMPLETED_BY_PT_STATUS)+ }+ Ok(payment_methods::NetworkTokenGenerationOutcome::NotApplicable) => {+ TaskOutcome::Finished(NOT_APPLICABLE_STATUS)+ }+ Err(err) => TaskOutcome::Failed(err),+ })}+ }+}- let platform = crate::types::domain::Platform::new(- merchant_account.clone(),- key_store.clone(),- merchant_account,- key_store,- None,- );+/// Records the outcome of a run on the process tracker entry: a terminal outcome finishes the+/// task, a failure is retried until the retry budget for payment methods is exhausted.+async fn finish_task(+ state: &SessionState,+ process: storage::ProcessTracker,+ payment_method_id: &str,+ outcome: TaskOutcome,+) -> Result<(), errors::ProcessTrackerError> {+ let db = &*state.store;+ let retry_count = process.retry_count;- let result = Box::pin(tokenization::generate_network_token_for_payment_method(- state,- &platform,- &tracking_data,- payment_method,- ))- .await;-- match result {- Ok(()) => {- db.as_scheduler()- .finish_process_with_business_status(process, "COMPLETED_BY_PT")- .await- .map_err(Into::<errors::ProcessTrackerError>::into)?;- }- Err(err) => {- logger::error!(- payment_method_id=%tracking_data.payment_method_id,- ?err,- "Failed to generate network token in process tracker workflow"- );- let mapping = process_data::PaymentMethodsPTMapping::default();- let time_delta = if retry_count == 0 {- Some(mapping.default_mapping.start_after)- } else {- pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)- };- let schedule_time = pt_utils::get_time_from_delta(time_delta);- match schedule_time {- Some(s_time) => db- .as_scheduler()- .retry_process(process, s_time)- .await- .map_err(Into::<errors::ProcessTrackerError>::into)?,- None => db- .as_scheduler()- .finish_process_with_business_status(process, "RETRIES_EXCEEDED")- .await- .map_err(Into::<errors::ProcessTrackerError>::into)?,- };- }+ match outcome {+ TaskOutcome::Finished(business_status) => {+ db.as_scheduler()+ .finish_process_with_business_status(process, business_status)+ .await?;}+ TaskOutcome::Failed(err) => {+ logger::error!(+ payment_method_id=%payment_method_id,+ ?err,+ "Failed to generate network token in process tracker workflow"+ );- Ok(())- }+ let mapping = process_data::PaymentMethodsPTMapping::default();+ let time_delta = if retry_count == 0 {+ Some(mapping.default_mapping.start_after)+ } else {+ pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)+ };- #[cfg(feature = "v2")]- async fn execute_workflow<'a>(- &'a self,- _state: &'a SessionState,- _process: storage::ProcessTracker,- ) -> Result<(), errors::ProcessTrackerError> {- todo!()+ match pt_utils::get_time_from_delta(time_delta) {+ Some(schedule_time) => {+ db.as_scheduler()+ .retry_process(process, schedule_time)+ .await?;+ }+ None => {+ logger::error!(+ payment_method_id=%payment_method_id,+ "Exhausted all retries to generate a network token for this payment method"+ );+ db.as_scheduler()+ .finish_process_with_business_status(process, RETRIES_EXCEEDED_STATUS)+ .await?;+ }+ }+ }}- async fn error_handler<'a>(- &'a self,- _state: &'a SessionState,- process: storage::ProcessTracker,- _error: errors::ProcessTrackerError,- ) -> errors::CustomResult<(), errors::ProcessTrackerError> {- logger::error!(%process.id, "Failed while executing NetworkTokenizationWorkflow");- Ok(())- }+ Ok(())}diff --git a/crates/subscriptions/src/core/payments_api_client.rs b/crates/subscriptions/src/core/payments_api_client.rsindex 2b67f395c6..32296d5394 100644--- a/crates/subscriptions/src/core/payments_api_client.rs+++ b/crates/subscriptions/src/core/payments_api_client.rs@@ -80,7 +80,7 @@ impl PaymentsApiClient {}let request = request_builder.build();- let response = api::call_connector_api(state, request, "Subscription Payments")+ let response = api::call_connector_api(state, request, "Subscription Payments", None).await.change_context(subscription_error.clone())?;