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(scheduler): add task segregation based on application source (#10505)
Kashif08f0afbebfff
diff --git a/config/config.example.toml b/config/config.example.tomlindex 59bcb13782..56c948699a 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -2,6 +2,11 @@# all the available configuration options, and is intended to be used# solely as a reference. Please copy this file to create a config.+# This is used to identify the running application instance+# Check common_enums::ApplicationSource for available options+# For more details - https://github.com/juspay/hyperswitch/issues/10489+application_source = "main"+# Server configuration[server]port = 8080@@ -416,6 +421,7 @@ cards = [# It defines the streams/queues name and configuration as well as event selection variables[scheduler]stream = "SCHEDULER_STREAM"+cug_stream = "CUG_SCHEDULER_STREAM"graceful_shutdown_interval = 60000 # Specifies how much time to wait while re-attempting shutdown for a service (in milliseconds)loop_interval = 5000 # Specifies how much time to wait before starting the defined behaviour of producer or consumer (in milliseconds)diff --git a/config/development.toml b/config/development.tomlindex 63d1f35982..7378310129 100644--- a/config/development.toml+++ b/config/development.toml@@ -1,3 +1,5 @@+application_source = "main"+[log.file]enabled = false@@ -382,6 +384,7 @@ zsl.base_url = "https://api.sitoffalb.net/"[scheduler]stream = "SCHEDULER_STREAM"+cug_stream = "CUG_SCHEDULER_STREAM"[scheduler.consumer]disabled = false@@ -1444,4 +1447,4 @@ token = "123456" # Superposition tokenorg_id = "localorg" # Organization ID in Superpositionworkspace_id = "dev" # Workspace ID in Superpositionpolling_interval = 15 # Polling interval in seconds for configuration updates-# request_timeout = # Request timeout in seconds for Superposition API calls (optional, default: none)\ No newline at end of file+# request_timeout = # Request timeout in seconds for Superposition API calls (optional, default: none)diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex dfefb23ae6..a418e782de 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -9966,6 +9966,28 @@ pub enum ProcessTrackerRunner {InvoiceSyncflow,}+#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[router_derive::diesel_enum(storage_type = "text")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum ApplicationSource {+ #[default]+ Main,+ Cug,+}+#[derive(Debug)]pub enum CryptoPadding {PKCS7,diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rsindex 3b060f299a..79acee7f45 100644--- a/crates/diesel_models/src/process_tracker.rs+++ b/crates/diesel_models/src/process_tracker.rs@@ -5,7 +5,10 @@ use error_stack::ResultExt;use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;-use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult};+use crate::{+ enums as storage_enums, enums::ApplicationSource, errors, schema::process_tracker,+ StorageResult,+};#[derive(Clone,@@ -40,6 +43,7 @@ pub struct ProcessTracker {#[serde(with = "common_utils::custom_serde::iso8601")]pub updated_at: PrimitiveDateTime,pub version: ApiVersion,+ pub application_source: Option<ApplicationSource>,}impl ProcessTracker {@@ -66,6 +70,7 @@ pub struct ProcessTrackerNew {pub created_at: PrimitiveDateTime,pub updated_at: PrimitiveDateTime,pub version: ApiVersion,+ pub application_source: Option<ApplicationSource>,}impl ProcessTrackerNew {@@ -79,6 +84,7 @@ impl ProcessTrackerNew {retry_count: Option<i32>,schedule_time: PrimitiveDateTime,api_version: ApiVersion,+ application_source: ApplicationSource,) -> StorageResult<Self>whereT: Serialize + std::fmt::Debug,@@ -102,6 +108,7 @@ impl ProcessTrackerNew {created_at: current_time,updated_at: current_time,version: api_version,+ application_source: Some(application_source),})}}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 705746a668..cac9fcf117 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -1426,6 +1426,8 @@ diesel::table! {created_at -> Timestamp,updated_at -> Timestamp,version -> ApiVersion,+ #[max_length = 64]+ application_source -> Nullable<Varchar>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 1ead8e4093..ff5d7383d1 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -1371,6 +1371,8 @@ diesel::table! {created_at -> Timestamp,updated_at -> Timestamp,version -> ApiVersion,+ #[max_length = 64]+ application_source -> Nullable<Varchar>,}}diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 8cf32ca456..a6522c76b6 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -489,6 +489,7 @@ pub(crate) async fn fetch_raw_secrets(Settings {server: conf.server,+ application_source: conf.application_source,chat,master_database,redis: conf.redis,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 1255d8907b..6fca1eb9c4 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -7,6 +7,7 @@ use std::{#[cfg(feature = "olap")]use analytics::{opensearch::OpenSearchConfig, ReportConfig};use api_models::enums;+use common_enums;use common_utils::{ext_traits::ConfigExt, id_type, types::user::EmailThemeConfig};use config::{Environment, File};use error_stack::ResultExt;@@ -73,6 +74,7 @@ pub struct CmdLineConf {#[serde(default)]pub struct Settings<S: SecretState> {pub server: Server,+ pub application_source: common_enums::ApplicationSource,pub proxy: Proxy,pub env: Env,pub chat: SecretStateContainer<ChatSettings, S>,diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rsindex b6d1b8d739..8eeae7bda1 100644--- a/crates/router/src/core/api_keys.rs+++ b/crates/router/src/core/api_keys.rs@@ -171,10 +171,15 @@ pub async fn create_api_key(if api_key.expires_at.is_some() {let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();- add_api_key_expiry_task(store, &api_key, expiry_reminder_days)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to insert API key expiry reminder to process tracker")?;+ add_api_key_expiry_task(+ store,+ &api_key,+ expiry_reminder_days,+ state.conf.application_source,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert API key expiry reminder to process tracker")?;}}@@ -193,6 +198,7 @@ pub async fn add_api_key_expiry_task(store: &dyn crate::db::StorageInterface,api_key: &ApiKey,expiry_reminder_days: Vec<u8>,+ application_source: common_enums::ApplicationSource,) -> Result<(), errors::ProcessTrackerError> {let current_time = date_time::now();@@ -231,6 +237,7 @@ pub async fn add_api_key_expiry_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct API key expiry process tracker task")?;@@ -346,12 +353,15 @@ pub async fn update_api_key(else if api_key.expires_at.is_some() {// Process doesn't exist in process_tracker table, so create new entry with// schedule_time based on new expiry set.- add_api_key_expiry_task(store, &api_key, expiry_reminder_days)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to insert API key expiry reminder task to process tracker",- )?;+ add_api_key_expiry_task(+ store,+ &api_key,+ expiry_reminder_days,+ state.conf.application_source,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert API key expiry reminder task to process tracker")?;}}diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex e4a7c56992..be477f0707 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -12,6 +12,8 @@ use router_env::{use strum::IntoEnumIterator;pub mod transformers;+use common_enums;+use super::{errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt},metrics,@@ -843,6 +845,7 @@ pub async fn fetch_disputes_from_connector(dispute,merchant_id.clone(),schedule_time,+ state.conf.application_source,).await;@@ -917,6 +920,7 @@ pub async fn add_process_dispute_task_to_pt(dispute_payload: &DisputeSyncResponse,merchant_id: common_utils::id_type::MerchantId,schedule_time: Option<time::PrimitiveDateTime>,+ application_source: common_enums::ApplicationSource,) -> common_utils::errors::CustomResult<(), errors::StorageError> {match schedule_time {Some(time) => {@@ -947,6 +951,7 @@ pub async fn add_process_dispute_task_to_pt(None,time,common_types::consts::API_VERSION,+ application_source,).map_err(errors::StorageError::from)?;db.insert_process(process_tracker_entry).await?;@@ -964,6 +969,7 @@ pub async fn add_dispute_list_task_to_pt(merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,profile_id: common_utils::id_type::ProfileId,fetch_request: FetchDisputesRequestData,+ application_source: common_enums::ApplicationSource,) -> common_utils::errors::CustomResult<(), errors::StorageError> {TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "dispute_list")));let tracking_data = disputes::DisputeListPTData {@@ -992,6 +998,7 @@ pub async fn add_dispute_list_task_to_pt(None,fetch_request.created_from,common_types::consts::API_VERSION,+ application_source,).map_err(errors::StorageError::from)?;db.insert_process(process_tracker_entry).await?;@@ -1028,6 +1035,7 @@ pub async fn schedule_dispute_sync_task(let merchant_id = mca.merchant_id.clone();let merchant_connector_id = mca.merchant_connector_id.clone();let business_profile_id = business_profile.get_id().clone();+ let application_source = state.conf.application_source;tokio::spawn(async move {@@ -1041,6 +1049,7 @@ pub async fn schedule_dispute_sync_task(created_from,created_till,},+ application_source,).await.map_err(|error| {diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 75a4b2f6c5..692e0e30f0 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -453,6 +453,7 @@ pub async fn add_payment_method_status_update_task(prev_status: enums::PaymentMethodStatus,curr_status: enums::PaymentMethodStatus,merchant_id: &id_type::MerchantId,+ application_source: common_enums::ApplicationSource,) -> Result<(), ProcessTrackerError> {let created_at = payment_method.created_at;let schedule_time =@@ -483,6 +484,7 @@ pub async fn add_payment_method_status_update_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?;diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 31a138bee3..260b71bb4e 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -869,6 +869,7 @@ impl PaymentMethodsController for PmCards<'_> {prev_status,curr_status,merchant_id,+ self.state.conf.application_source,).await}@@ -1367,6 +1368,7 @@ pub async fn get_client_secret_or_add_payment_method(enums::PaymentMethodStatus::AwaitingData,enums::PaymentMethodStatus::Inactive,merchant_id,+ state.conf.application_source,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -4968,6 +4970,7 @@ impl TempLockerCardSupport {&*state.store,&lookup_key,enums::PaymentMethod::Card,+ state.conf.application_source,).await?;metrics::TOKENIZED_DATA_COUNT.add(1, &[]);diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 218d6288c3..ff12241481 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -1173,7 +1173,13 @@ impl Vault {merchant_key_store.key.get_inner(),).await?;- add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;+ add_delete_tokenized_data_task(+ &*state.store,+ &lookup_key,+ pm,+ state.conf.application_source,+ )+ .await?;metrics::TOKENIZED_DATA_COUNT.add(1, &[]);Ok(lookup_key)}@@ -2201,6 +2207,7 @@ pub async fn add_delete_tokenized_data_task(db: &dyn db::StorageInterface,lookup_key: &str,pm: enums::PaymentMethod,+ application_source: common_enums::ApplicationSource,) -> RouterResult<()> {let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;let process_tracker_id = format!("{runner}_{lookup_key}");@@ -2224,6 +2231,7 @@ pub async fn add_delete_tokenized_data_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct delete tokenized data process tracker task")?;diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 8cce6cc29c..ee97116722 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -8781,6 +8781,7 @@ pub async fn add_process_sync_task(db: &dyn StorageInterface,payment_attempt: &storage::PaymentAttempt,schedule_time: time::PrimitiveDateTime,+ application_source: enums::ApplicationSource,) -> CustomResult<(), errors::StorageError> {let tracking_data = api::PaymentsRetrieveRequest {force_sync: true,@@ -8806,6 +8807,7 @@ pub async fn add_process_sync_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).map_err(errors::StorageError::from)?;diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex f204f063ee..680d3e0377 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -1437,10 +1437,15 @@ where1,router_env::metric_attributes!(("flow", format!("{:#?}", operation))),);- super::add_process_sync_task(&*state.store, payment_attempt, stime)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed while adding task to process tracker")+ super::add_process_sync_task(+ &*state.store,+ payment_attempt,+ stime,+ state.conf.application_source,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while adding task to process tracker")} else {// When the requeue is true, we reset the tasks count as we reset the task every time it is requeuedmetrics::TASKS_RESET_COUNT.add(diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 1e220af3a8..2f2bacf9e3 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -1293,6 +1293,7 @@ pub async fn create_recipient(&*state.store,payout_data,common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)),+ state.conf.application_source,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -3200,6 +3201,7 @@ pub async fn add_external_account_addition_task(db: &dyn StorageInterface,payout_data: &PayoutData,schedule_time: time::PrimitiveDateTime,+ application_source: common_enums::ApplicationSource,) -> CustomResult<(), errors::StorageError> {let runner = storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow;let task = "STRPE_ATTACH_EXTERNAL_ACCOUNT";@@ -3224,6 +3226,7 @@ pub async fn add_external_account_addition_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).map_err(errors::StorageError::from)?;diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex 47316b529b..1923be79ff 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -1713,7 +1713,7 @@ pub async fn schedule_refund_execution(// Execute the refund task based on refund_typematch refund_type {api_models::refunds::RefundType::Scheduled => {- add_refund_execute_task(db, &refund, runner)+ add_refund_execute_task(db, &refund, runner, state.conf.application_source).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.refund_id))?;@@ -1735,7 +1735,7 @@ pub async fn schedule_refund_execution(match update_refund {Ok((updated_refund_data, raw_connector_response)) => {- add_refund_sync_task(db, &updated_refund_data, runner)+ add_refund_sync_task(db, &updated_refund_data, runner, state.conf.application_source).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!(@@ -1754,7 +1754,7 @@ pub async fn schedule_refund_execution(//[#300]: return refund status responsematch refund_type {api_models::refunds::RefundType::Scheduled => {- add_refund_sync_task(db, &refund, runner)+ add_refund_sync_task(db, &refund, runner, state.conf.application_source).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id))?;@@ -1983,6 +1983,7 @@ pub async fn trigger_refund_execute_workflow(db,&updated_refund,storage::ProcessTrackerRunner::RefundWorkflowRouter,+ state.conf.application_source,).await?;}@@ -1992,6 +1993,7 @@ pub async fn trigger_refund_execute_workflow(db,&refund,storage::ProcessTrackerRunner::RefundWorkflowRouter,+ state.conf.application_source,).await?;}@@ -2026,6 +2028,7 @@ pub async fn add_refund_sync_task(db: &dyn db::StorageInterface,refund: &diesel_refund::Refund,runner: storage::ProcessTrackerRunner,+ application_source: common_enums::ApplicationSource,) -> RouterResult<storage::ProcessTracker> {let task = "SYNC_REFUND";let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);@@ -2046,6 +2049,7 @@ pub async fn add_refund_sync_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct refund sync process tracker task")?;@@ -2070,6 +2074,7 @@ pub async fn add_refund_execute_task(db: &dyn db::StorageInterface,refund: &diesel_refund::Refund,runner: storage::ProcessTrackerRunner,+ application_source: common_enums::ApplicationSource,) -> RouterResult<storage::ProcessTracker> {let task = "EXECUTE_REFUND";let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);@@ -2085,6 +2090,7 @@ pub async fn add_refund_execute_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct refund execute process tracker task")?;diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rsindex 1c397e5067..1759f80649 100644--- a/crates/router/src/core/refunds_v2.rs+++ b/crates/router/src/core/refunds_v2.rs@@ -1360,7 +1360,7 @@ pub async fn schedule_refund_execution(// Execute the refund task based on refund_typematch refund_type {api_models::refunds::RefundType::Scheduled => {- add_refund_execute_task(db, &refund, runner)+ add_refund_execute_task(db, &refund, runner, state.conf.application_source).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?;@@ -1405,7 +1405,7 @@ pub async fn schedule_refund_execution(match update_refund {Ok((updated_refund_data, raw_connector_response)) => {- add_refund_sync_task(db, &updated_refund_data, runner)+ add_refund_sync_task(db, &updated_refund_data, runner, state.conf.application_source).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!(@@ -1424,7 +1424,7 @@ pub async fn schedule_refund_execution(//[#300]: return refund status responsematch refund_type {api_models::refunds::RefundType::Scheduled => {- add_refund_sync_task(db, &refund, runner)+ add_refund_sync_task(db, &refund, runner, state.conf.application_source).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?;@@ -1463,6 +1463,7 @@ pub async fn add_refund_execute_task(db: &dyn db::StorageInterface,refund: &diesel_refund::Refund,runner: storage::ProcessTrackerRunner,+ application_source: common_enums::ApplicationSource,) -> errors::RouterResult<storage::ProcessTracker> {let task = "EXECUTE_REFUND";let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());@@ -1478,6 +1479,7 @@ pub async fn add_refund_execute_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct refund execute process tracker task")?;@@ -1500,6 +1502,7 @@ pub async fn add_refund_sync_task(db: &dyn db::StorageInterface,refund: &diesel_refund::Refund,runner: storage::ProcessTrackerRunner,+ application_source: common_enums::ApplicationSource,) -> errors::RouterResult<storage::ProcessTracker> {let task = "SYNC_REFUND";let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());@@ -1515,6 +1518,7 @@ pub async fn add_refund_sync_task(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct refund sync process tracker task")?;diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex fbbbbd1117..630cbb7d1f 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -57,9 +57,11 @@ use crate::{pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW";pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW";pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW";-use common_enums::enums::ProcessTrackerStatus;+#[cfg(feature = "v1")]+use crate::types::common_enums;+#[allow(clippy::too_many_arguments)]pub async fn upsert_calculate_pcr_task(billing_connector_account: &domain::MerchantConnectorAccount,@@ -140,6 +142,7 @@ pub async fn upsert_calculate_pcr_task(Some(1),schedule_time,common_types::consts::API_VERSION,+ state.conf.application_source,).change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError).attach_printable("Failed to construct calculate workflow process tracker entry")?;@@ -382,6 +385,7 @@ pub async fn perform_execute_payment(attempt_id.clone(),storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,tracking_data.revenue_recovery_retry,+ state.conf.application_source,).await?;@@ -453,6 +457,7 @@ async fn insert_psync_pcr_task_to_pt(payment_attempt_id: id_type::GlobalAttemptId,runner: storage::ProcessTrackerRunner,revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,+ application_source: common_enums::ApplicationSource,) -> RouterResult<storage::ProcessTracker> {let task = PSYNC_WORKFLOW;let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner);@@ -476,6 +481,7 @@ async fn insert_psync_pcr_task_to_pt(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to construct delete tokenized data process tracker task")?;@@ -988,6 +994,7 @@ async fn insert_execute_pcr_task_to_pt(Some(1),schedule_time,common_types::consts::API_VERSION,+ state.conf.application_source,).map_err(|e| {logger::error!(diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex 31ae2998d1..28272e79d4 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -790,6 +790,7 @@ impl Action {payment_attempt.id.clone(),storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,revenue_recovery_payment_data.retry_algorithm,+ state.conf.application_source,).await.change_context(errors::RecoveryError::ProcessTrackerFailure)@@ -1407,6 +1408,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure(Some(new_retry_count),schedule_time,common_types::consts::API_VERSION,+ state.conf.application_source,).change_context(errors::RecoveryError::ProcessTrackerFailure).attach_printable("Failed to construct calculate workflow process tracker entry")?;diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rsindex e3156d4292..2ed7ab7a22 100644--- a/crates/router/src/core/webhooks/outgoing.rs+++ b/crates/router/src/core/webhooks/outgoing.rs@@ -201,6 +201,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(&*state.store,&business_profile,&event,+ state.conf.application_source,).await.inspect_err(|error| {@@ -568,6 +569,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(db: &dyn StorageInterface,business_profile: &domain::Profile,event: &domain::Event,+ application_source: common_enums::ApplicationSource,) -> CustomResult<storage::ProcessTracker, errors::StorageError> {let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time(db,@@ -608,6 +610,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(None,schedule_time,common_types::consts::API_VERSION,+ application_source,).map_err(errors::StorageError::from)?;diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 576a6bb0d5..420bd58c6f 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -150,6 +150,9 @@ impl scheduler::SchedulerSessionState for SessionState {fn get_db(&self) -> Box<dyn SchedulerInterface> {self.store.get_scheduler_db()}+ fn get_application_source(&self) -> common_enums::ApplicationSource {+ self.conf.application_source+ }}impl SessionState {pub fn set_store(&mut self, store: Box<dyn StorageInterface>) {diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rsindex 7d5611f83e..67904cf4cc 100644--- a/crates/router/src/types/domain/types.rs+++ b/crates/router/src/types/domain/types.rs@@ -88,6 +88,7 @@ impl From<app::SessionState> for subscriptions::state::SubscriptionState {.clone(),internal_services: state.conf.internal_services.clone(),connectors: state.conf.connectors.clone(),+ application_source: state.conf.application_source,},tenant: state.tenant.clone(),event_handler: Box::new(state.event_handler.clone()),diff --git a/crates/router/src/workflows/dispute_list.rs b/crates/router/src/workflows/dispute_list.rsindex 2c5fc8c4b9..2f2ffb9c50 100644--- a/crates/router/src/workflows/dispute_list.rs+++ b/crates/router/src/workflows/dispute_list.rs@@ -77,6 +77,7 @@ impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow {.dispute_polling_interval.unwrap_or_default().deref();+ let application_source = state.conf.application_source;tokio::spawn(async move {@@ -84,6 +85,7 @@ impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow {&*m_db,&m_tracking_data,dispute_polling_interval,+ application_source,).await.map_err(|error| {@@ -198,6 +200,7 @@ pub async fn schedule_next_dispute_list_task(db: &dyn StorageInterface,tracking_data: &api::DisputeListPTData,dispute_polling_interval: i32,+ application_source: common_enums::ApplicationSource,) -> Result<(), errors::ProcessTrackerError> {let new_created_till = tracking_data.created_till@@ -216,6 +219,7 @@ pub async fn schedule_next_dispute_list_task(tracking_data.merchant_connector_id.clone(),tracking_data.profile_id.clone(),fetch_request,+ application_source,).await?;Ok(())diff --git a/crates/scheduler/src/configs/defaults.rs b/crates/scheduler/src/configs/defaults.rsindex d17c20829e..1bc16874be 100644--- a/crates/scheduler/src/configs/defaults.rs+++ b/crates/scheduler/src/configs/defaults.rs@@ -2,6 +2,7 @@ impl Default for super::settings::SchedulerSettings {fn default() -> Self {Self {stream: "SCHEDULER_STREAM".into(),+ cug_stream: "CUG_SCHEDULER_STREAM".into(),producer: super::settings::ProducerSettings::default(),consumer: super::settings::ConsumerSettings::default(),graceful_shutdown_interval: 60000,diff --git a/crates/scheduler/src/configs/settings.rs b/crates/scheduler/src/configs/settings.rsindex 0135c9dcf4..b5209eeba3 100644--- a/crates/scheduler/src/configs/settings.rs+++ b/crates/scheduler/src/configs/settings.rs@@ -5,6 +5,7 @@ use serde::Deserialize;#[serde(default)]pub struct SchedulerSettings {pub stream: String,+ pub cug_stream: String,pub producer: ProducerSettings,pub consumer: ConsumerSettings,pub loop_interval: u64,diff --git a/crates/scheduler/src/configs/validations.rs b/crates/scheduler/src/configs/validations.rsindex 06052f9ff6..6f3bb7c08c 100644--- a/crates/scheduler/src/configs/validations.rs+++ b/crates/scheduler/src/configs/validations.rs@@ -11,6 +11,12 @@ impl super::settings::SchedulerSettings {))})?;+ when(self.cug_stream.is_default_or_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "scheduler cug_stream must not be empty".into(),+ ))+ })?;+when(self.consumer.consumer_group.is_default_or_empty(), || {Err(ApplicationError::InvalidConfigurationValueError("scheduler consumer group must not be empty".into(),diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rsindex f2d5da4ab9..a938b8bd5b 100644--- a/crates/scheduler/src/consumer.rs+++ b/crates/scheduler/src/consumer.rs@@ -139,7 +139,10 @@ pub async fn consumer_operations<T: SchedulerSessionState + 'static>(settings: &SchedulerSettings,workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,) -> CustomResult<(), errors::ProcessTrackerError> {- let stream_name = settings.stream.clone();+ let stream_name = match state.get_application_source() {+ enums::ApplicationSource::Main => settings.stream.clone(),+ enums::ApplicationSource::Cug => settings.cug_stream.clone(),+ };let group_name = settings.consumer.consumer_group.clone();let consumer_name = format!("consumer_{}", Uuid::new_v4());diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rsindex 1d72197376..8d9396472c 100644--- a/crates/scheduler/src/db/process_tracker.rs+++ b/crates/scheduler/src/db/process_tracker.rs@@ -250,6 +250,7 @@ impl ProcessTrackerInterface for MockDb {created_at: new.created_at,updated_at: new.updated_at,version: new.version,+ application_source: new.application_source,};processes.push(process.clone());Ok(process)diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rsindex f1e915323f..9417c3c143 100644--- a/crates/scheduler/src/producer.rs+++ b/crates/scheduler/src/producer.rs@@ -110,12 +110,25 @@ wheredebug!("Producer count of tasks {}", tasks.len());// [#268]: Allow task based segregation of tasks+ let (cug_tasks, main_tasks): (Vec<storage::ProcessTracker>, Vec<storage::ProcessTracker>) =+ tasks.into_iter().partition(|task| {+ task.application_source == Some(diesel_models::enums::ApplicationSource::Cug)+ });divide_and_append_tasks(state.get_db().as_scheduler(),SchedulerFlow::Producer,- tasks,+ main_tasks,settings,+ diesel_models::enums::ApplicationSource::Main,+ )+ .await?;+ divide_and_append_tasks(+ state.get_db().as_scheduler(),+ SchedulerFlow::Producer,+ cug_tasks,+ settings,+ diesel_models::enums::ApplicationSource::Cug,).await?;diff --git a/crates/scheduler/src/scheduler.rs b/crates/scheduler/src/scheduler.rsindex 7a5681147a..35c03aa4d4 100644--- a/crates/scheduler/src/scheduler.rs+++ b/crates/scheduler/src/scheduler.rs@@ -56,6 +56,7 @@ pub trait SchedulerAppState: Send + Sync + Clone {}#[async_trait::async_trait]pub trait SchedulerSessionState: Send + Sync + Clone {+ fn get_application_source(&self) -> diesel_models::enums::ApplicationSource;fn get_db(&self) -> Box<dyn SchedulerInterface>;}pub async fn start_process_tracker<diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rsindex 078a6e2297..c4e0ed2ad0 100644--- a/crates/scheduler/src/utils.rs+++ b/crates/scheduler/src/utils.rs@@ -22,13 +22,18 @@ pub async fn divide_and_append_tasks<T>(flow: SchedulerFlow,tasks: Vec<storage::ProcessTracker>,settings: &SchedulerSettings,+ application_source: enums::ApplicationSource,) -> CustomResult<(), errors::ProcessTrackerError>whereT: SchedulerInterface + Send + Sync + ?Sized,{- let batches = divide(tasks, settings);+ let batches = divide(tasks, settings, application_source);// Safety: Assuming we won't deal with more than `u64::MAX` batches at once- logger::info!("Adding {} batches to stream", batches.len());+ logger::info!(+ "Adding {} batches for application_source: {:?}",+ batches.len(),+ application_source+ );#[allow(clippy::as_conversions)]metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metricsfor batch in batches {@@ -148,10 +153,11 @@ wherepub fn divide(tasks: Vec<storage::ProcessTracker>,conf: &SchedulerSettings,+ application_source: enums::ApplicationSource,) -> Vec<ProcessTrackerBatch> {let now = common_utils::date_time::now();let batch_size = conf.producer.batch_size;- divide_into_batches(batch_size, tasks, now, conf)+ divide_into_batches(batch_size, tasks, now, conf, application_source)}pub fn divide_into_batches(@@ -159,16 +165,22 @@ pub fn divide_into_batches(tasks: Vec<storage::ProcessTracker>,batch_creation_time: time::PrimitiveDateTime,conf: &SchedulerSettings,+ application_source: enums::ApplicationSource,) -> Vec<ProcessTrackerBatch> {let batch_id = Uuid::new_v4().to_string();+ let stream_name = match application_source {+ enums::ApplicationSource::Main => &conf.stream,+ enums::ApplicationSource::Cug => &conf.cug_stream,+ };+tasks.chunks(batch_size).fold(Vec::new(), |mut batches, item| {let batch = ProcessTrackerBatch {id: batch_id.clone(),group_name: conf.consumer.consumer_group.clone(),- stream_name: conf.stream.clone(),+ stream_name: stream_name.to_string(),connection_name: String::new(),created_time: batch_creation_time,rule: String::new(), // is it required?diff --git a/crates/subscriptions/src/state.rs b/crates/subscriptions/src/state.rsindex 9d2a74f8ba..ea0defd3d9 100644--- a/crates/subscriptions/src/state.rs+++ b/crates/subscriptions/src/state.rs@@ -61,6 +61,7 @@ pub struct SubscriptionConfig {pub internal_merchant_id_profile_id_auth: configs::InternalMerchantIdProfileIdAuthSettings,pub internal_services: configs::InternalServicesConfig,pub connectors: configs::Connectors,+ pub application_source: common_enums::ApplicationSource,}impl From<&SubscriptionState> for keymanager::KeyManagerState {diff --git a/crates/subscriptions/src/workflows/invoice_sync.rs b/crates/subscriptions/src/workflows/invoice_sync.rsindex 08141be9f5..6d1b526937 100644--- a/crates/subscriptions/src/workflows/invoice_sync.rs+++ b/crates/subscriptions/src/workflows/invoice_sync.rs@@ -411,6 +411,7 @@ pub async fn create_invoice_sync_job(Some(0),common_utils::date_time::now(),common_types::consts::API_VERSION,+ state.conf.application_source,).change_context(router_errors::ApiErrorResponse::InternalServerError).attach_printable("subscriptions: unable to form process_tracker type")?;diff --git a/migrations/2025-12-01-113559_add_application_source_to_process_tracker/down.sql b/migrations/2025-12-01-113559_add_application_source_to_process_tracker/down.sqlnew file mode 100644index 0000000000..1c76f262c0--- /dev/null+++ b/migrations/2025-12-01-113559_add_application_source_to_process_tracker/down.sql@@ -0,0 +1,2 @@+-- Drop the application_source column from the process_tracker table if it exists+ALTER TABLE process_tracker DROP COLUMN IF EXISTS application_source;diff --git a/migrations/2025-12-01-113559_add_application_source_to_process_tracker/up.sql b/migrations/2025-12-01-113559_add_application_source_to_process_tracker/up.sqlnew file mode 100644index 0000000000..d58cd6312f--- /dev/null+++ b/migrations/2025-12-01-113559_add_application_source_to_process_tracker/up.sql@@ -0,0 +1,2 @@+-- Add the application_source column to the process_tracker table if it does not exist+ALTER TABLE process_tracker ADD COLUMN IF NOT EXISTS application_source VARCHAR(64);