Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(routing): add decision engine rule migration and status endpoints (#13745)

Jagan8eef08f08ec8
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index 9b014a773a..bfc62e3569 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -5,9 +5,10 @@ use crate::routing::{
CreateDynamicRoutingWrapper, DynamicRoutingUpdateConfigQuery, EliminationRoutingPayloadWrapper,
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingEntryResponse,
- RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
- RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit,
- RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery,
+ RoutingKind, RoutingLinkWrapper, RoutingMigrationStatusQuery, RoutingMigrationStatusResponse,
+ RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper,
+ RoutingRetrieveQuery, RoutingVolumeSplit, RoutingVolumeSplitResponse,
+ RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery, RuleMigrationRequest,
RuleMigrationResponse, RuleMigrationResult, SuccessBasedRoutingConfig,
SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingPath, ToggleDynamicRoutingQuery,
ToggleDynamicRoutingWrapper,
@@ -173,6 +174,24 @@ impl ApiEventMetric for RuleMigrationQuery {
}
}
+impl ApiEventMetric for RuleMigrationRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for RoutingMigrationStatusQuery {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for RoutingMigrationStatusResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
impl ApiEventMetric for RuleMigrationResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs
index 7cc8d47fca..83f79cbbd4 100644
--- a/crates/api_models/src/open_router.rs
+++ b/crates/api_models/src/open_router.rs
@@ -539,6 +539,99 @@ pub struct MerchantAccount {
pub gateway_success_rate_based_decider_input: Option<String>,
}
+/// How much of the account tree a handed-over Decision Engine session may move within. Mirrors
+/// the Hyperswitch role that opened it, so the session is never broader than its origin.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum GrantLevel {
+ Profile,
+ Merchant,
+ Org,
+}
+
+/// Request for a one-time Decision Engine SSO handoff code. Carries the profile to land on plus
+/// the user's grant and permissions, both omitted for an API key — which falls back to one profile.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct MerchantTokenRequest {
+ /// The profile the session lands on. A Decision Engine routing scope *is* a Hyperswitch
+ /// profile, which is why this field is named for a merchant but carries a profile id.
+ pub merchant_id: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub grant_level: Option<GrantLevel>,
+ /// The org or merchant id `grant_level` names. Unused for a profile grant, whose node is
+ /// `merchant_id`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub grant_id: Option<String>,
+ /// What the user may do, as Decision Engine spells it (`routing:read`, `routing:write`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub permissions: Option<Vec<String>>,
+ /// Display only, so the dashboard can name the user rather than show a profile id.
+ /// Authorization comes from the grant and permissions, never from this.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+}
+
+/// Account hierarchy pushed to the Decision Engine. A DE scope is a Hyperswitch profile; the
+/// levels above are ancestry, used to group profiles, resolve merchant-level config, and scope
+/// API keys. Hyperswitch is the only side that knows the tree. Upserted, so safe to resend.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct HierarchySyncRequest {
+ pub orgs: Vec<HierarchyOrg>,
+ /// Detecting merchant-id-keyed scopes makes DE read every merchant account, so it is off for
+ /// per-profile calls and on for the bulk backfill.
+ pub report_stranded: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct HierarchyOrg {
+ pub org_id: String,
+ pub org_name: Option<String>,
+ pub merchants: Vec<HierarchyMerchant>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct HierarchyMerchant {
+ /// The HS merchant account id — ancestry, never a DE routing scope.
+ pub merchant_id: String,
+ pub merchant_name: Option<String>,
+ pub profiles: Vec<HierarchyProfile>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct HierarchyProfile {
+ /// The HS profile id — this *is* the DE routing scope.
+ pub profile_id: String,
+ pub profile_name: Option<String>,
+}
+
+impl HierarchySyncRequest {
+ /// Tree carrying exactly one profile, for provisioning a single scope.
+ pub fn single_profile(
+ org_id: String,
+ org_name: Option<String>,
+ merchant_id: String,
+ merchant_name: Option<String>,
+ profile_id: String,
+ profile_name: Option<String>,
+ ) -> Self {
+ Self {
+ orgs: vec![HierarchyOrg {
+ org_id,
+ org_name,
+ merchants: vec![HierarchyMerchant {
+ merchant_id,
+ merchant_name,
+ profiles: vec![HierarchyProfile {
+ profile_id,
+ profile_name,
+ }],
+ }],
+ }],
+ report_stranded: false,
+ }
+ }
+}
+
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FetchRoutingConfig {
pub merchant_id: String,
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 2fbcc18b3a..f321585d13 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -582,6 +582,23 @@ pub enum RoutingAlgorithmKind {
ThreeDsDecisionRule,
}
+impl RoutingAlgorithmKind {
+ /// Why `/routing/rule/migrate` does not carry this kind, or `None` when it does. Both
+ /// excluded kinds reach the decision engine another way, so a rule migration that leaves
+ /// them behind is finished, not partial.
+ pub fn rule_migration_exclusion(self) -> Option<&'static str> {
+ match self {
+ Self::Single | Self::Priority | Self::VolumeSplit | Self::Advanced => None,
+ Self::Dynamic => {
+ Some("dynamic routing configuration, provisioned by the dynamic routing setup")
+ }
+ Self::ThreeDsDecisionRule => {
+ Some("3DS decision rules are not held in the decision engine rule store")
+ }
+ }
+ }
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingPayloadWrapper {
pub updated_config: Vec<RoutableConnectorChoice>,
@@ -1851,10 +1868,155 @@ impl RuleMigrationQuery {
}
}
+/// Migrate a batch of profiles, named explicitly so a run's blast radius is in the request.
+/// Each profile's merchant is resolved from its rules, so no contradictory pair is expressible.
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct RuleMigrationRequest {
+ pub profile_ids: Vec<common_utils::id_type::ProfileId>,
+ /// Rules read per profile, not per batch.
+ pub limit: Option<u32>,
+ pub offset: Option<u32>,
+}
+
+impl RuleMigrationRequest {
+ pub fn validated_limit(&self) -> u32 {
+ self.limit.unwrap_or(50).min(1000)
+ }
+}
+
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationResult {
+ pub profiles: Vec<RuleMigrationProfileResult>,
+ pub totals: RuleMigrationTotals,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct RuleMigrationProfileResult {
+ pub profile_id: common_utils::id_type::ProfileId,
+ /// Absent when the profile holds no rules.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub success: Vec<RuleMigrationResponse>,
+ /// Already in the decision engine, left alone. Apart from `errors` so a finished migration
+ /// is distinguishable from a failed one.
+ pub skipped: Vec<RuleMigrationSkipped>,
pub errors: Vec<RuleMigrationError>,
+ /// Rules this endpoint does not carry, listed so a profile can still reach a clean finish.
+ /// Retrying will never move them, which is what separates these from `errors`.
+ pub not_applicable: Vec<RuleMigrationNotApplicable>,
+ /// Nothing was attempted: no rules, or the merchant could not be read. Per-rule failures
+ /// are `errors`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub not_attempted: Option<String>,
+}
+
+/// A rule outside this endpoint's scope, with the reason it is out of scope.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct RuleMigrationNotApplicable {
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ pub kind: RoutingAlgorithmKind,
+ pub reason: String,
+}
+
+#[derive(Debug, Default, serde::Serialize)]
+pub struct RuleMigrationTotals {
+ pub profiles: usize,
+ pub rules_migrated: usize,
+ pub rules_skipped: usize,
+ pub rules_failed: usize,
+ pub rules_not_applicable: usize,
+ pub profiles_not_attempted: usize,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct RoutingMigrationStatusQuery {
+ pub limit: Option<u32>,
+ pub offset: Option<u32>,
+}
+
+impl RoutingMigrationStatusQuery {
+ /// Each profile costs a decision engine call, so the page size bounds the work.
+ pub fn validated_limit(&self) -> u32 {
+ self.limit.unwrap_or(50).min(500)
+ }
+}
+
+/// Where one profile stands in the migration. The order is the lifecycle.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RoutingMigrationState {
+ /// Rules exist in Hyperswitch and none of them are in the decision engine.
+ Pending,
+ /// Some rules made it across and some did not — a dual-write that failed, usually.
+ Partial,
+ /// Both sides hold rules, but not the same ones — counts can match, so ids are compared.
+ Diverged,
+ /// Every rule is in the decision engine, and Hyperswitch is still routing.
+ Migrated,
+ /// Cut over: the decision engine decides this profile's routing.
+ Enabled,
+ /// Cut over with rules missing, so traffic falls through to the default connector list.
+ /// The one state that is actively wrong rather than unfinished.
+ EnabledWithoutRules,
+ /// Something could not be read, so no claim is made. Never conflated with a zero.
+ Unknown,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct RoutingMigrationProfileStatus {
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ /// Counts only the kinds a rule migration carries, so it can be compared with the decision
+ /// engine directly. Dynamic and 3DS rules are `rules_out_of_scope`.
+ pub rules_hyperswitch: i64,
+ /// Held by Hyperswitch but never migrated by this endpoint — see
+ /// [`RoutingAlgorithmKind::rule_migration_exclusion`].
+ pub rules_out_of_scope: i64,
+ /// `None` when the decision engine could not be reached for this profile.
+ pub rules_decision_engine: Option<i64>,
+ /// Held by Hyperswitch, absent in the decision engine — what a migration run would write.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub rules_missing_in_decision_engine: Vec<String>,
+ /// Held by the decision engine, absent in Hyperswitch. Migration does not remove them.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub rules_only_in_decision_engine: Vec<String>,
+ /// The cut-over as configured, not as enforced — the diff kill switch can suppress it at
+ /// runtime. `None` when unresolved, which is not the same as "on Hyperswitch".
+ pub routing_source: Option<RoutingResultSource>,
+ pub state: RoutingMigrationState,
+}
+
+/// Counts for the returned page only — an estate-wide total would mean scanning everything.
+#[derive(Debug, Default, serde::Serialize)]
+pub struct RoutingMigrationPageTotals {
+ pub profiles: usize,
+ pub pending: usize,
+ pub partial: usize,
+ pub migrated: usize,
+ pub enabled: usize,
+ pub enabled_without_rules: usize,
+ pub diverged: usize,
+ pub unknown: usize,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct RoutingMigrationStatusResponse {
+ pub profiles: Vec<RoutingMigrationProfileStatus>,
+ pub limit: u32,
+ pub offset: u32,
+ /// The page came back full, so another is worth asking for.
+ pub has_more: bool,
+ pub page_totals: RoutingMigrationPageTotals,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct RuleMigrationSkipped {
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ pub decision_engine_algorithm_id: String,
+ /// This run linked it as the profile's active rule.
+ pub linked_active_rule: bool,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/diesel_models/src/query/routing_algorithm.rs b/crates/diesel_models/src/query/routing_algorithm.rs
index 227ef45a9f..69ce7edb2e 100644
--- a/crates/diesel_models/src/query/routing_algorithm.rs
+++ b/crates/diesel_models/src/query/routing_algorithm.rs
@@ -139,6 +139,9 @@ impl RoutingAlgorithm {
dsl::algorithm_for,
))
.filter(dsl::profile_id.eq(profile_id.to_owned()))
+ // `algorithm_id` breaks ties on `modified_at`, which bulk-created rules share. Without
+ // a total order the pages of one limit/offset walk overlap and leave rules unvisited.
+ .order((dsl::modified_at.desc(), dsl::algorithm_id.asc()))
.limit(limit)
.offset(offset)
.load_async::<(
@@ -206,7 +209,8 @@ impl RoutingAlgorithm {
)
.limit(limit)
.offset(offset)
- .order(dsl::modified_at.desc())
+ // `algorithm_id` breaks ties on `modified_at`, so the pages of one walk stay disjoint.
+ .order((dsl::modified_at.desc(), dsl::algorithm_id.asc()))
.load_async::<(
common_utils::id_type::ProfileId,
common_utils::id_type::RoutingId,
@@ -274,7 +278,8 @@ impl RoutingAlgorithm {
.filter(dsl::algorithm_for.eq(transaction_type.to_owned()))
.limit(limit)
.offset(offset)
- .order(dsl::modified_at.desc())
+ // `algorithm_id` breaks ties on `modified_at`, so the pages of one walk stay disjoint.
+ .order((dsl::modified_at.desc(), dsl::algorithm_id.asc()))
.load_async::<(
common_utils::id_type::ProfileId,
common_utils::id_type::RoutingId,
@@ -313,4 +318,63 @@ impl RoutingAlgorithm {
)
.collect())
}
+
+ /// Every rule id held by the given profiles, with each profile's merchant — taken from here
+ /// rather than `business_profile`, which is encrypted and needs the merchant to read. The
+ /// kind rides along so callers can tell which rules a migration is expected to carry.
+ pub async fn rule_ids_for_profiles(
+ conn: &PgPooledConn,
+ profile_ids: &[common_utils::id_type::ProfileId],
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::RoutingId,
+ enums::RoutingAlgorithmKind,
+ )>,
+ > {
+ Self::table()
+ .select((
+ dsl::profile_id,
+ dsl::merchant_id,
+ dsl::algorithm_id,
+ dsl::kind,
+ ))
+ .filter(dsl::profile_id.eq_any(profile_ids.to_vec()))
+ .order((dsl::profile_id.asc(), dsl::algorithm_id.asc()))
+ .load_async::<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::RoutingId,
+ enums::RoutingAlgorithmKind,
+ )>(conn)
+ .await
+ .change_context(DatabaseError::Others)
+ }
+
+ /// A page of the profiles that hold routing rules. Grouped so the page is of profiles —
+ /// paginating per rule would split one across pages. Ordered so paging is stable.
+ pub async fn list_scope_page(
+ conn: &PgPooledConn,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ )>,
+ > {
+ Self::table()
+ .group_by((dsl::merchant_id, dsl::profile_id))
+ .select((dsl::profile_id, dsl::merchant_id))
+ .order((dsl::merchant_id.asc(), dsl::profile_id.asc()))
+ .limit(limit)
+ .offset(offset)
+ .load_async::<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ )>(conn)
+ .await
+ .change_context(DatabaseError::Others)
+ }
}
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 2400ed4986..cf94b275ca 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -1,6 +1,6 @@
pub mod helpers;
pub mod transformers;
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing::DynamicRoutingAlgoAccessor;
@@ -65,16 +65,114 @@ use crate::{
types::{
api, domain,
storage::{self, enums as storage_enums},
- transformers::{ForeignInto, ForeignTryFrom},
+ transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{self, OptionExt},
};
+/// Describes the dashboard user to the Decision Engine: which part of the tree the session may
+/// move within, and what it may do there. States the user's position rather than a list of scopes;
+/// DE resolves it against its own synced tree. Falls back to a bare profile request if the role
+/// cannot be read.
+#[cfg(all(feature = "olap", feature = "v1"))]
+async fn decision_engine_token_request(
+ state: &SessionState,
+ profile_id: &common_utils::id_type::ProfileId,
+ user: crate::services::authentication::UserFromToken,
+) -> api_models::open_router::MerchantTokenRequest {
+ use api_models::open_router::{GrantLevel, MerchantTokenRequest};
+ use common_enums::EntityType;
+
+ // Looked up rather than read from the token, which carries only the user id. Display only, so
+ // a failure here costs a name in the dashboard and nothing else.
+ let email = match state.global_store.find_user_by_user_id(&user.user_id).await {
+ Ok(found) => {
+ // `Email` wraps a `Secret`, so it takes both traits to reach the string.
+ use hyperswitch_masking::{ExposeInterface, PeekInterface};
+ Some(
+ domain::UserFromStorage::from(found)
+ .get_email()
+ .expose()
+ .peek()
+ .to_string(),
+ )
+ }
+ Err(error) => {
+ router_env::logger::warn!(
+ ?error,
+ "decision_engine_euclid: could not read email for SSO handoff"
+ );
+ None
+ }
+ };
+
+ let profile_only = MerchantTokenRequest {
+ merchant_id: profile_id.get_string_repr().to_string(),
+ grant_level: None,
+ grant_id: None,
+ permissions: None,
+ email: email.clone(),
+ };
+
+ let role_info =
+ match crate::services::authorization::roles::RoleInfo::from_role_id_org_id_tenant_id(
+ state,
+ &user.role_id,
+ &user.org_id,
+ user.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
+ )
+ .await
+ {
+ Ok(role_info) => role_info,
+ Err(error) => {
+ // Never fails the handoff: the user is already authorized for this endpoint, so the
+ // worst outcome of an unreadable role is the narrower session they had before.
+ router_env::logger::warn!(
+ ?error,
+ "decision_engine_euclid: could not read role for SSO handoff, falling back to profile scope"
+ );
+ return profile_only;
+ }
+ };
+
+ let (grant_level, grant_id) = match role_info.get_entity_type() {
+ // A tenant role spans every org, which is not a node the tree can name. Treated as the org
+ // the session is currently in, rather than granting more than one org at once.
+ EntityType::Tenant | EntityType::Organization => (
+ GrantLevel::Org,
+ Some(user.org_id.get_string_repr().to_string()),
+ ),
+ EntityType::Merchant => (
+ GrantLevel::Merchant,
+ Some(user.merchant_id.get_string_repr().to_string()),
+ ),
+ EntityType::Profile => (GrantLevel::Profile, None),
+ };
+
+ // Read is implied — this endpoint sits behind ProfileRoutingRead, so reaching it at all means
+ // the role has it. Only write has to be asked about.
+ let mut permissions = vec!["routing:read".to_string()];
+ if role_info.check_permission_exists(
+ crate::services::authorization::permissions::Permission::ProfileRoutingWrite,
+ ) {
+ permissions.push("routing:write".to_string());
+ }
+
+ MerchantTokenRequest {
+ merchant_id: profile_id.get_string_repr().to_string(),
+ grant_level: Some(grant_level),
+ grant_id,
+ permissions: Some(permissions),
+ email,
+ }
+}
+
/// Dashboard routing entry: reports the profile's routing source and, for a cut-over profile with a `target`, returns a one-time DE dashboard deep-link.
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn routing_entry(
state: SessionState,
platform: domain::Platform,
+ user: crate::services::authentication::UserFromToken,
profile_id: Option<common_utils::id_type::ProfileId>,
target: Option<routing_types::DecisionEngineRoutingTarget>,
) -> RouterResponse<routing_types::RoutingEntryResponse> {
@@ -94,7 +192,10 @@ pub async fn routing_entry(
// Mint a fresh one-time code only when a card was clicked (`target`) on a cut-over profile.
let redirect_url = match (is_cutover, target) {
(true, Some(target)) => {
- let code = match helpers::mint_decision_engine_sso_code(&state, &profile_id).await {
+ let token_request = decision_engine_token_request(&state, &profile_id, user).await;
+ let code = match helpers::mint_decision_engine_sso_code(&state, token_request.clone())
+ .await
+ {
Ok(code) => code,
// Provision the DE merchant only when it does not exist yet (DE returns 404), then retry once.
Err(err)
@@ -106,8 +207,34 @@ pub async fn routing_entry(
}
) =>
{
- let _ = helpers::create_decision_engine_merchant(&state, &profile_id).await;
- helpers::mint_decision_engine_sso_code(&state, &profile_id)
+ // Provision with ancestry so a scope created on this path is grouped under its
+ // merchant, rather than landing in DE unattached. Falls back to the bare
+ // create if the profile cannot be read, since minting a code for a merchant
+ // that exists without ancestry still beats failing the dashboard entry.
+ let processor = platform.get_processor();
+ match core_utils::validate_and_get_business_profile(
+ state.store.as_ref(),
+ processor,
+ Some(&profile_id),
+ )
+ .await
+ .ok()
+ .flatten()
+ {
+ Some(profile) => {
+ let _ = helpers::sync_decision_engine_hierarchy(
+ &state,
+ processor.get_account(),
+ &profile,
+ )
+ .await;
+ }
+ None => {
+ let _ =
+ helpers::create_decision_engine_merchant(&state, &profile_id).await;
+ }
+ }
+ helpers::mint_decision_engine_sso_code(&state, token_request)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
}
@@ -477,7 +604,29 @@ pub async fn create_routing_algorithm_under_profile(
let mut decision_engine_routing_id: Option<String> = None;
- if let Some(euclid_algorithm) = request.algorithm.clone() {
+ // Provision the scope before dual-writing into it: DE does not verify the scope exists, and
+ // a rule attached to one with no merchant account routes fine but breaks the dashboard handoff.
+ // Non-fatal and gating on purpose — merchants must be able to create rules while DE is down.
+ // A skipped write shows as pending in the reconciliation report and re-migrating repairs it.
+ let de_scope_provisioned = match helpers::sync_decision_engine_hierarchy(
+ &state,
+ processor.get_account(),
+ &business_profile,
+ )
+ .await
+ {
+ Ok(()) => true,
+ Err(err) => {
+ router_env::logger::warn!(
+ decision_engine_error = ?err,
+ profile_id = ?profile_id.get_string_repr(),
+ "decision_engine_euclid: skipping rule dual-write, scope could not be provisioned"
+ );
+ false
+ }
+ };
+
+ if let Some(euclid_algorithm) = request.algorithm.clone().filter(|_| de_scope_provisioned) {
let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm {
EuclidAlgorithm::Advanced(program) => match program.try_into() {
Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)),
@@ -2547,14 +2696,163 @@ pub async fn reset_decision_engine_diff_counter(
Ok(service_api::ApplicationResponse::StatusOk)
}
-pub async fn migrate_rules_for_profile(
+/// A merchant account and its key store, by id. Migration works from
+/// `routing_algorithm.merchant_id` rather than an authenticated context, so it resolves its own.
+async fn get_merchant_account(
+ state: &SessionState,
+ merchant_id: &common_utils::id_type::MerchantId,
+) -> RouterResult<(
+ hyperswitch_domain_models::platform::MerchantKeyStore,
+ domain::MerchantAccount,
+)> {
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(merchant_id, &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ Ok((key_store, merchant_account))
+}
+
+/// Migrates the named profiles' rules into the decision engine. One profile failing does not
+/// stop the batch; a profile with no rules is reported as not attempted rather than as an error.
+pub async fn migrate_rules_for_profiles(
state: SessionState,
- processor: domain::Processor,
- query_params: routing_types::RuleMigrationQuery,
+ request: routing_types::RuleMigrationRequest,
) -> RouterResult<routing_types::RuleMigrationResult> {
+ let limit = request.validated_limit();
+ let offset = request.offset.unwrap_or_default();
+
+ let merchant_of: HashMap<_, _> = state
+ .store
+ .find_rule_ids_for_profiles(&request.profile_ids)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?
+ .into_iter()
+ .map(|(profile_id, merchant_id, _, _)| (profile_id, merchant_id))
+ .collect();
+
+ let mut profiles = Vec::with_capacity(request.profile_ids.len());
+ let mut totals = routing_types::RuleMigrationTotals {
+ profiles: request.profile_ids.len(),
+ ..Default::default()
+ };
+
+ // Once per merchant, before the loop: profiles cluster under merchants, and each read is two
+ // store lookups plus decryption.
+ let mut accounts: HashMap<common_utils::id_type::MerchantId, domain::Processor> =
+ HashMap::new();
+ let mut unreadable_merchants: HashSet<common_utils::id_type::MerchantId> = HashSet::new();
+
+ for merchant_id in merchant_of.values().cloned().collect::<HashSet<_>>() {
+ match get_merchant_account(&state, &merchant_id).await {
+ Ok((key_store, merchant_account)) => {
+ let platform = domain::Platform::new(
+ merchant_account.clone(),
+ key_store.clone(),
+ merchant_account,
+ key_store,
+ None,
+ );
+ accounts.insert(merchant_id, platform.get_processor().clone());
+ }
+ Err(err) => {
+ router_env::logger::error!(
+ ?err,
+ merchant_id = ?merchant_id.get_string_repr(),
+ "could not read merchant account while migrating rules"
+ );
+ unreadable_merchants.insert(merchant_id);
+ }
+ }
+ }
+
+ for profile_id in request.profile_ids {
+ let Some(merchant_id) = merchant_of.get(&profile_id).cloned() else {
+ profiles.push(routing_types::RuleMigrationProfileResult {
+ profile_id,
+ merchant_id: None,
+ success: vec![],
+ skipped: vec![],
+ errors: vec![],
+ not_applicable: vec![],
+ not_attempted: Some("no routing rules in Hyperswitch".to_string()),
+ });
+ totals.profiles_not_attempted += 1;
+ continue;
+ };
+
+ let Some(processor) = accounts.get(&merchant_id).cloned() else {
+ let reason = if unreadable_merchants.contains(&merchant_id) {
+ "merchant account could not be read"
+ } else {
+ "merchant account not resolved"
+ };
+ profiles.push(routing_types::RuleMigrationProfileResult {
+ profile_id,
+ merchant_id: Some(merchant_id),
+ success: vec![],
+ skipped: vec![],
+ errors: vec![],
+ not_applicable: vec![],
+ not_attempted: Some(reason.to_string()),
+ });
+ totals.profiles_not_attempted += 1;
+ continue;
+ };
+
+ match migrate_rules_for_profile(&state, processor, profile_id.clone(), limit, offset).await
+ {
+ Ok(result) => {
+ totals.rules_migrated += result.success.len();
+ totals.rules_skipped += result.skipped.len();
+ totals.rules_failed += result.errors.len();
+ totals.rules_not_applicable += result.not_applicable.len();
+ profiles.push(result);
+ }
+ Err(err) => {
+ router_env::logger::error!(
+ ?err,
+ profile_id = ?profile_id.get_string_repr(),
+ "profile could not be migrated"
+ );
+ profiles.push(routing_types::RuleMigrationProfileResult {
+ profile_id,
+ merchant_id: Some(merchant_id),
+ success: vec![],
+ skipped: vec![],
+ errors: vec![],
+ not_applicable: vec![],
+ not_attempted: Some(err.current_context().to_string()),
+ });
+ totals.profiles_not_attempted += 1;
+ }
+ }
+ }
+
+ Ok(routing_types::RuleMigrationResult { profiles, totals })
+}
+
+/// Migrates one profile's rules. The batch entry point is `migrate_rules_for_profiles`.
+async fn migrate_rules_for_profile(
+ state: &SessionState,
+ processor: domain::Processor,
+ profile_id: common_utils::id_type::ProfileId,
+ limit: u32,
+ offset: u32,
+) -> RouterResult<routing_types::RuleMigrationProfileResult> {
use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm;
- let profile_id = query_params.profile_id.clone();
+ let state = state.clone();
let db = state.store.as_ref();
let business_profile =
@@ -2565,6 +2863,12 @@ pub async fn migrate_rules_for_profile(
id: profile_id.get_string_repr().to_owned(),
})?;
+ // Provision the scope, with its ancestry, before migrating any rule into it — otherwise the
+ // rules route but the dashboard handoff returns "merchant not found".
+ helpers::sync_decision_engine_hierarchy(&state, processor.get_account(), &business_profile)
+ .await
+ .attach_printable("Failed to provision decision engine scope before rule migration")?;
+
#[cfg(feature = "v1")]
let active_payment_routing_ids: Vec<Option<common_utils::id_type::RoutingId>> = vec![
business_profile
@@ -2586,14 +2890,41 @@ pub async fn migrate_rules_for_profile(
.store
.list_routing_algorithm_metadata_by_profile_id(
&profile_id,
- i64::from(query_params.validated_limit()),
- i64::from(query_params.offset.unwrap_or_default()),
+ i64::from(limit),
+ i64::from(offset),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ // The decision engine keys rule create on the Hyperswitch algorithm id, so re-writing an
+ // existing rule is a key conflict — without this a finished migration reads as total failure.
+ // A read failure here is not fatal: the set stays empty and every rule is attempted.
+ let already_in_decision_engine: HashSet<String> = match list_de_euclid_routing_algorithms(
+ &state,
+ ListRountingAlgorithmsRequest {
+ created_by: profile_id.get_string_repr().to_string(),
+ },
+ )
+ .await
+ {
+ Ok(records) => records
+ .into_iter()
+ .map(|record| record.id.get_string_repr().to_string())
+ .collect(),
+ Err(err) => {
+ router_env::logger::warn!(
+ decision_engine_error = ?err,
+ profile_id = ?profile_id.get_string_repr(),
+ "decision_engine_euclid: could not list existing rules, migrating without skipping"
+ );
+ HashSet::new()
+ }
+ };
+
let mut response_list = Vec::new();
+ let mut skipped_list = Vec::new();
let mut error_list = Vec::new();
+ let mut not_applicable_list = Vec::new();
let mut push_error = |algorithm_id, msg: String| {
error_list.push(RuleMigrationError {
@@ -2605,6 +2936,55 @@ pub async fn migrate_rules_for_profile(
for routing_metadata in routing_metadatas {
let algorithm_id = routing_metadata.algorithm_id.clone();
+
+ // Held apart from `errors`: these kinds are not Euclid rules, so parsing one as an
+ // algorithm fails every time and would keep a finished profile looking incomplete.
+ let kind = routing_types::RoutingAlgorithmKind::foreign_from(routing_metadata.kind);
+ if let Some(reason) = kind.rule_migration_exclusion() {
+ not_applicable_list.push(routing_types::RuleMigrationNotApplicable {
+ profile_id: profile_id.clone(),
+ algorithm_id,
+ kind,
+ reason: reason.to_string(),
+ });
+ continue;
+ }
+
+ // Already migrated. The rule is left untouched — an insert cannot repair diverged
+ // contents anyway. Linking is still attempted: a rule can arrive without being made
+ // that profile's active one.
+ if already_in_decision_engine.contains(algorithm_id.get_string_repr()) {
+ let is_active_rule = active_payment_routing_ids.contains(&Some(algorithm_id.clone()));
+ let mut linked_active_rule = false;
+ if is_active_rule {
+ match link_de_euclid_routing_algorithm(
+ &state,
+ ActivateRoutingConfigRequest {
+ created_by: profile_id.get_string_repr().to_string(),
+ routing_algorithm_id: algorithm_id.get_string_repr().to_string(),
+ },
+ )
+ .await
+ {
+ Ok(()) => linked_active_rule = true,
+ Err(err) => {
+ router_env::logger::warn!(
+ decision_engine_error = ?err,
+ algorithm_id = ?algorithm_id,
+ "decision_engine_euclid: could not link an already-migrated active rule"
+ );
+ }
+ }
+ }
+ skipped_list.push(routing_types::RuleMigrationSkipped {
+ profile_id: profile_id.clone(),
+ algorithm_id: algorithm_id.clone(),
+ decision_engine_algorithm_id: algorithm_id.get_string_repr().to_string(),
+ linked_active_rule,
+ });
+ continue;
+ }
+
let algorithm = match db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
@@ -2665,7 +3045,9 @@ pub async fn migrate_rules_for_profile(
let routing_rule = RoutingRule {
rule_id: Some(algorithm.algorithm_id.clone().get_string_repr().to_string()),
name: algorithm.name.clone(),
- description: algorithm.description.clone(),
+ // The decision engine requires a description; the column here is nullable, and a
+ // null one is rejected outright rather than migrated.
+ description: Some(algorithm.description.clone().unwrap_or_default()),
created_by: profile_id.get_string_repr().to_string(),
algorithm: static_algorithm,
algorithm_for: algorithm.algorithm_for.into(),
@@ -2711,9 +3093,178 @@ pub async fn migrate_rules_for_profile(
}
}
- Ok(routing_types::RuleMigrationResult {
+ Ok(routing_types::RuleMigrationProfileResult {
+ profile_id,
+ merchant_id: Some(processor.get_account().get_id().clone()),
success: response_list,
+ skipped: skipped_list,
errors: error_list,
+ not_applicable: not_applicable_list,
+ not_attempted: None,
+ })
+}
+
+/// Where every profile holding a routing rule stands in the migration, a page at a time. Each
+/// source is read independently and its absence reported as unknown rather than assumed.
+pub async fn routing_migration_status(
+ state: SessionState,
+ query: routing_types::RoutingMigrationStatusQuery,
+) -> RouterResult<routing_types::RoutingMigrationStatusResponse> {
+ let limit = query.validated_limit();
+ let offset = query.offset.unwrap_or_default();
+
+ let scopes = state
+ .store
+ .list_routing_scope_page(i64::from(limit), i64::from(offset))
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ // The page's rule ids in one query, so the comparison below costs nothing per profile.
+ let page_profiles: Vec<_> = scopes
+ .iter()
+ .map(|(profile_id, _)| profile_id.clone())
+ .collect();
+ let mut hs_rule_ids: HashMap<common_utils::id_type::ProfileId, HashSet<String>> =
+ HashMap::new();
+ // Rules the migration is not expected to carry, counted apart so holding one never leaves a
+ // finished profile reading as partial.
+ let mut out_of_scope: HashMap<common_utils::id_type::ProfileId, i64> = HashMap::new();
+ match state.store.find_rule_ids_for_profiles(&page_profiles).await {
+ Ok(rows) => {
+ for (profile_id, _, algorithm_id, kind) in rows {
+ if routing_types::RoutingAlgorithmKind::foreign_from(kind)
+ .rule_migration_exclusion()
+ .is_some()
+ {
+ *out_of_scope.entry(profile_id).or_default() += 1;
+ continue;
+ }
+ hs_rule_ids
+ .entry(profile_id)
+ .or_default()
+ .insert(algorithm_id.get_string_repr().to_string());
+ }
+ }
+ Err(err) => {
+ router_env::logger::warn!(?err, "could not read rule ids while reporting status");
+ }
+ }
+
+ let has_more = scopes.len() == usize::try_from(limit).unwrap_or(usize::MAX);
+ let mut profiles = Vec::with_capacity(scopes.len());
+ let mut page_totals = routing_types::RoutingMigrationPageTotals {
+ profiles: scopes.len(),
+ ..Default::default()
+ };
+
+ for (profile_id, merchant_id) in scopes {
+ // The listing already carries each rule's id, so comparing the sets is free.
+ let de_rule_ids = match list_de_euclid_routing_algorithms(
+ &state,
+ ListRountingAlgorithmsRequest {
+ created_by: profile_id.get_string_repr().to_string(),
+ },
+ )
+ .await
+ {
+ Ok(records) => Some(
+ records
+ .into_iter()
+ .map(|record| record.id.get_string_repr().to_string())
+ .collect::<HashSet<_>>(),
+ ),
+ Err(err) => {
+ router_env::logger::warn!(
+ decision_engine_error = ?err,
+ profile_id = ?profile_id.get_string_repr(),
+ "decision_engine_euclid: could not read rules while reporting migration status"
+ );
+ None
+ }
+ };
+
+ let rules_decision_engine = de_rule_ids
+ .as_ref()
+ .map(|ids| i64::try_from(ids.len()).unwrap_or(i64::MAX));
+
+ let hs_ids = hs_rule_ids.get(&profile_id).cloned().unwrap_or_default();
+ let rules_hyperswitch = i64::try_from(hs_ids.len()).unwrap_or(i64::MAX);
+ let (mut missing_in_de, mut only_in_de) = (Vec::new(), Vec::new());
+ if let Some(de_ids) = de_rule_ids.as_ref() {
+ missing_in_de = hs_ids.difference(de_ids).cloned().collect();
+ only_in_de = de_ids.difference(&hs_ids).cloned().collect();
+ missing_in_de.sort();
+ only_in_de.sort();
+ }
+
+ // The *configured* cut-over. `get_routing_result_source` would overlay Hyperswitch
+ // routing when the diff counter is over threshold — right for a payment, wrong here: a
+ // tripped kill switch would turn a runtime condition into a migration verdict.
+ let dimensions = dimension_state::Dimensions::new()
+ .with_processor_merchant_id(merchant_id.clone().into())
+ .with_provider_merchant_id(
+ hyperswitch_domain_models::platform::ProviderMerchantId::new(merchant_id.clone()),
+ )
+ .with_profile_id(profile_id.clone());
+ let routing_source = Some(
+ dimensions
+ .get_routing_result_source(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await,
+ );
+
+ let cut_over = matches!(
+ routing_source,
+ Some(routing_types::RoutingResultSource::DecisionEngine)
+ );
+ // `Partial` and `Diverged` both mean rules are missing; `Diverged` also means the counts
+ // agree, so nothing that only counts will surface it.
+ let state_of_profile = match rules_decision_engine {
+ None => routing_types::RoutingMigrationState::Unknown,
+ Some(0) if cut_over => routing_types::RoutingMigrationState::EnabledWithoutRules,
+ Some(0) => routing_types::RoutingMigrationState::Pending,
+ Some(count) if !missing_in_de.is_empty() && count == rules_hyperswitch => {
+ routing_types::RoutingMigrationState::Diverged
+ }
+ Some(_) if !missing_in_de.is_empty() => routing_types::RoutingMigrationState::Partial,
+ Some(_) if cut_over => routing_types::RoutingMigrationState::Enabled,
+ Some(_) => routing_types::RoutingMigrationState::Migrated,
+ };
+
+ match state_of_profile {
+ routing_types::RoutingMigrationState::Pending => page_totals.pending += 1,
+ routing_types::RoutingMigrationState::Partial => page_totals.partial += 1,
+ routing_types::RoutingMigrationState::Migrated => page_totals.migrated += 1,
+ routing_types::RoutingMigrationState::Enabled => page_totals.enabled += 1,
+ routing_types::RoutingMigrationState::EnabledWithoutRules => {
+ page_totals.enabled_without_rules += 1
+ }
+ routing_types::RoutingMigrationState::Diverged => page_totals.diverged += 1,
+ routing_types::RoutingMigrationState::Unknown => page_totals.unknown += 1,
+ }
+
+ profiles.push(routing_types::RoutingMigrationProfileStatus {
+ rules_out_of_scope: out_of_scope.get(&profile_id).copied().unwrap_or_default(),
+ profile_id,
+ merchant_id,
+ rules_hyperswitch,
+ rules_decision_engine,
+ rules_missing_in_decision_engine: missing_in_de,
+ rules_only_in_decision_engine: only_in_de,
+ routing_source,
+ state: state_of_profile,
+ });
+ }
+
+ Ok(routing_types::RoutingMigrationStatusResponse {
+ profiles,
+ limit,
+ offset,
+ has_more,
+ page_totals,
})
}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 2399c08256..9452e10db6 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -8,9 +8,7 @@ use std::str::FromStr;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::sync::Arc;
-#[cfg(feature = "v1")]
-use api_models::open_router;
-use api_models::routing as routing_types;
+use api_models::{open_router, routing as routing_types};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use common_utils::ext_traits::ValueExt;
use common_utils::{ext_traits::Encode, id_type};
@@ -30,15 +28,14 @@ use external_services::grpc_client::dynamic_routing::{
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
-#[cfg(feature = "v1")]
-use router_env::logger;
-#[cfg(feature = "v1")]
-use router_env::{instrument, tracing};
+use router_env::{instrument, logger, tracing};
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use storage_impl::redis::cache::Cacheable;
+#[cfg(feature = "v1")]
+use crate::core::payments::{OperationSessionGetters, OperationSessionSetters};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::db::errors::StorageErrorExt;
#[cfg(feature = "v2")]
@@ -46,20 +43,16 @@ use crate::types::domain::MerchantConnectorAccount;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::types::transformers::ForeignFrom;
use crate::{
- core::errors::{self, RouterResult},
+ core::{
+ errors::{self, RouterResult},
+ payments::routing::utils::{self as routing_utils, DecisionEngineApiHandler},
+ },
db::StorageInterface,
routes::SessionState,
+ services,
types::{domain, storage},
utils::StringExt,
};
-#[cfg(feature = "v1")]
-use crate::{
- core::payments::{
- routing::utils::{self as routing_utils, DecisionEngineApiHandler},
- OperationSessionGetters, OperationSessionSetters,
- },
- services,
-};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::{
core::{metrics as core_metrics, routing},
@@ -79,6 +72,7 @@ pub const DECISION_ENGINE_RULE_GET_ENDPOINT: &str = "rule/get";
pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete";
pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account";
pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create";
+pub const DECISION_ENGINE_HIERARCHY_SYNC_ENDPOINT: &str = "admin/hierarchy/sync";
pub const DECISION_ENGINE_MERCHANT_TOKEN_ENDPOINT: &str = "auth/admin/merchant-token";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
@@ -2797,6 +2791,53 @@ pub async fn create_decision_engine_merchant(
Ok(())
}
+/// Provisions a Decision Engine scope for `profile` with the organization and merchant above it.
+///
+/// Prefer this over [`create_decision_engine_merchant`], which registers a scope with no ancestry.
+/// Upserted, so re-calling is a no-op. A failure must stop a rule migration: rules under a
+/// non-existent scope route correctly but break the dashboard handoff.
+#[instrument(skip_all)]
+pub async fn sync_decision_engine_hierarchy(
+ state: &SessionState,
+ merchant_account: &domain::MerchantAccount,
+ profile: &domain::Profile,
+) -> RouterResult<()> {
+ let request = open_router::HierarchySyncRequest::single_profile(
+ merchant_account
+ .organization_id
+ .get_string_repr()
+ .to_string(),
+ None,
+ merchant_account.get_id().get_string_repr().to_string(),
+ merchant_account
+ .merchant_name
+ .as_ref()
+ .map(|name| crate::pii::PeekInterface::peek(name.get_inner()).to_string()),
+ profile.get_id().get_string_repr().to_string(),
+ Some(profile.profile_name.clone()),
+ );
+
+ routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
+ state,
+ services::Method::Post,
+ DECISION_ENGINE_HIERARCHY_SYNC_ENDPOINT,
+ Some(request),
+ None,
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to sync account hierarchy to decision engine")?;
+
+ logger::info!(
+ profile_id = ?profile.get_id().get_string_repr(),
+ merchant_id = ?merchant_account.get_id().get_string_repr(),
+ "decision_engine_euclid: account hierarchy synced"
+ );
+
+ Ok(())
+}
+
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecisionEngineMerchantTokenResponse {
@@ -2804,17 +2845,15 @@ pub struct DecisionEngineMerchantTokenResponse {
}
/// Mint a one-time SSO handoff code from the Decision Engine for the profile (keyed on profile_id).
+///
+/// Carries the session's grant and permissions; both are omitted for a caller with no user behind
+/// it, which Decision Engine reads as a single profile with unrestricted access.
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn mint_decision_engine_sso_code(
state: &SessionState,
- profile_id: &id_type::ProfileId,
+ merchant_token_req: open_router::MerchantTokenRequest,
) -> error_stack::Result<String, errors::RoutingError> {
- let merchant_token_req = open_router::MerchantAccount {
- merchant_id: profile_id.get_string_repr().to_string(),
- gateway_success_rate_based_decider_input: None,
- };
-
let response: Option<DecisionEngineMerchantTokenResponse> =
routing_utils::ConfigApiClient::send_decision_engine_request(
state,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0c0b3f8577..0f28180dbc 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3500,6 +3500,33 @@ impl RoutingAlgorithmInterface for KafkaStore {
)
.await
}
+
+ async fn list_routing_scope_page(
+ &self,
+ limit: i64,
+ offset: i64,
+ ) -> CustomResult<Vec<(id_type::ProfileId, id_type::MerchantId)>, errors::StorageError> {
+ self.diesel_store
+ .list_routing_scope_page(limit, offset)
+ .await
+ }
+
+ async fn find_rule_ids_for_profiles(
+ &self,
+ profile_ids: &[id_type::ProfileId],
+ ) -> CustomResult<
+ Vec<(
+ id_type::ProfileId,
+ id_type::MerchantId,
+ id_type::RoutingId,
+ enums::RoutingAlgorithmKind,
+ )>,
+ errors::StorageError,
+ > {
+ self.diesel_store
+ .find_rule_ids_for_profiles(profile_ids)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/routing_algorithm.rs b/crates/router/src/db/routing_algorithm.rs
index 7b8397dd26..642b5abef9 100644
--- a/crates/router/src/db/routing_algorithm.rs
+++ b/crates/router/src/db/routing_algorithm.rs
@@ -1,4 +1,6 @@
-use diesel_models::{errors::DatabaseError, routing_algorithm as routing_storage};
+use diesel_models::{
+ enums as storage_enums, errors::DatabaseError, routing_algorithm as routing_storage,
+};
use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::mock_db::MockDb;
@@ -57,6 +59,29 @@ pub trait RoutingAlgorithmInterface {
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>;
+
+ async fn list_routing_scope_page(
+ &self,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ )>,
+ >;
+
+ async fn find_rule_ids_for_profiles(
+ &self,
+ profile_ids: &[common_utils::id_type::ProfileId],
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::RoutingId,
+ storage_enums::RoutingAlgorithmKind,
+ )>,
+ >;
}
#[async_trait::async_trait]
@@ -190,6 +215,43 @@ impl RoutingAlgorithmInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ #[instrument(skip_all)]
+ async fn list_routing_scope_page(
+ &self,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ )>,
+ > {
+ // Read connection: this scans every routing rule and only reports, so it does not belong
+ // on the pool live payments write through.
+ let conn = connection::pg_connection_read(self).await?;
+ routing_storage::RoutingAlgorithm::list_scope_page(&conn, limit, offset)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn find_rule_ids_for_profiles(
+ &self,
+ profile_ids: &[common_utils::id_type::ProfileId],
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::RoutingId,
+ storage_enums::RoutingAlgorithmKind,
+ )>,
+ > {
+ let conn = connection::pg_connection_read(self).await?;
+ routing_storage::RoutingAlgorithm::rule_ids_for_profiles(&conn, profile_ids)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -252,4 +314,31 @@ impl RoutingAlgorithmInterface for MockDb {
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
Err(errors::StorageError::MockDbError)?
}
+
+ async fn list_routing_scope_page(
+ &self,
+ _limit: i64,
+ _offset: i64,
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ )>,
+ > {
+ Err(errors::StorageError::MockDbError)?
+ }
+
+ async fn find_rule_ids_for_profiles(
+ &self,
+ _profile_ids: &[common_utils::id_type::ProfileId],
+ ) -> StorageResult<
+ Vec<(
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::RoutingId,
+ storage_enums::RoutingAlgorithmKind,
+ )>,
+ > {
+ Err(errors::StorageError::MockDbError)?
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 126375a026..99fac11cb2 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
#[cfg(all(feature = "olap", feature = "v1"))]
use api_models::routing::RoutingRetrieveQuery;
-use api_models::routing::RuleMigrationQuery;
+use api_models::routing::{RoutingMigrationStatusQuery, RuleMigrationRequest};
#[cfg(feature = "olap")]
use common_enums::{ExecutionMode, TransactionType};
#[cfg(feature = "partial-auth")]
@@ -1198,8 +1198,13 @@ impl Routing {
})),
)
.service(web::resource("/rule/migrate").route(web::post().to(
- |state, req, query: web::Query<RuleMigrationQuery>| {
- routing::migrate_routing_rules_for_profile(state, req, query)
+ |state, req, payload: web::Json<RuleMigrationRequest>| {
+ routing::migrate_routing_rules(state, req, payload)
+ },
+ )))
+ .service(web::resource("/migration/status").route(web::get().to(
+ |state, req, query: web::Query<RoutingMigrationStatusQuery>| {
+ routing::routing_migration_status(state, req, query)
},
)))
.service(
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5c2ed6923c..363b9425bb 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -89,6 +89,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::RoutingEvaluateRule
| Flow::DecisionEngineDiffCounterReset
| Flow::DecisionEngineRuleMigration
+ | Flow::DecisionEngineMigrationStatus
| Flow::VolumeSplitOnRoutingType
| Flow::DecisionEngineDecideGatewayCall
| Flow::DecisionEngineGatewayFeedbackCall => Self::Routing,
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index bf4622c8e6..62576662b0 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -12,7 +12,6 @@ use api_models::{
},
};
use error_stack::ResultExt;
-use hyperswitch_domain_models::platform::MerchantKeyStore;
use payment_methods::core::errors::ApiErrorResponse;
use router_env::{
tracing::{self, instrument},
@@ -25,11 +24,9 @@ use crate::{
payments::routing::utils::{DecisionEngineApiHandler, EuclidApiClient},
routing, surcharge_decision_config,
},
- db::errors::StorageErrorExt,
routes::AppState,
services,
services::{api as oss_api, authentication as auth, authorization::permissions::Permission},
- types::domain,
};
/// Dashboard routing entry: returns the profile's routing source and, with `?target`, a DE deep-link.
@@ -47,23 +44,21 @@ pub async fn routing_entry(
state,
&req,
(),
- move |state, auth: auth::AuthenticationData, _, _| {
+ // The user is carried alongside so the handoff can be scoped to what their Hyperswitch role
+ // actually reaches.
+ move |state, (auth, user): auth::AuthenticationDataWithUser, _, _| {
let platform = auth.platform;
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
- routing::routing_entry(state, platform, profile_id, target)
+ routing::routing_entry(state, platform, user, profile_id, target)
+ },
+ // Dashboard-only: the response is a deep link for a browser to follow, so there is no
+ // API-key caller to serve — and the handoff is scoped by the user's role, which a service
+ // credential does not have.
+ &auth::JWTAuth {
+ permission: Permission::ProfileRoutingRead,
+ allow_connected: true,
+ allow_platform: false,
},
- auth::auth_type(
- &auth::HeaderAuth(auth::ApiKeyAuth {
- allow_connected_scope_operation: true,
- allow_platform_self_operation: false,
- }),
- &auth::JWTAuth {
- permission: Permission::ProfileRoutingRead,
- allow_connected: true,
- allow_platform: false,
- },
- req.headers(),
- ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -1711,11 +1706,36 @@ pub async fn evaluate_routing_rule(
}
use actix_web::HttpResponse;
+
+/// Where every profile holding a routing rule stands in the migration, a page at a time.
+/// Read-only; paging bounds the work.
+#[instrument(skip_all, fields(flow = ?Flow::DecisionEngineMigrationStatus))]
+pub async fn routing_migration_status(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<routing_types::RoutingMigrationStatusQuery>,
+) -> impl Responder {
+ let flow = Flow::DecisionEngineMigrationStatus;
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ query.into_inner(),
+ |state, _, query_params, _| async move {
+ let res = Box::pin(routing::routing_migration_status(state, query_params)).await?;
+ Ok(services::ApplicationResponse::Json(res))
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::DecisionEngineRuleMigration))]
-pub async fn migrate_routing_rules_for_profile(
+pub async fn migrate_routing_rules(
state: web::Data<AppState>,
req: HttpRequest,
- query: web::Query<routing_types::RuleMigrationQuery>,
+ json_payload: web::Json<routing_types::RuleMigrationRequest>,
) -> HttpResponse {
let flow = Flow::DecisionEngineRuleMigration;
@@ -1723,23 +1743,9 @@ pub async fn migrate_routing_rules_for_profile(
flow,
state,
&req,
- query.into_inner(),
- |state, _, query_params, _| async move {
- let merchant_id = query_params.merchant_id.clone();
- let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
- let platform = domain::Platform::new(
- merchant_account.clone(),
- key_store.clone(),
- merchant_account,
- key_store,
- None,
- );
- let res = Box::pin(routing::migrate_rules_for_profile(
- state,
- platform.get_processor().clone(),
- query_params,
- ))
- .await?;
+ json_payload.into_inner(),
+ |state, _, payload, _| async move {
+ let res = Box::pin(routing::migrate_rules_for_profiles(state, payload)).await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
@@ -1768,28 +1774,6 @@ pub async fn reset_decision_engine_diff_counter(
.await
}
-async fn get_merchant_account(
- state: &super::SessionState,
- merchant_id: &common_utils::id_type::MerchantId,
-) -> common_utils::errors::CustomResult<(MerchantKeyStore, domain::MerchantAccount), ApiErrorResponse>
-{
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(merchant_id, &key_store)
- .await
- .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;
- Ok((key_store, merchant_account))
-}
-
#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn call_decide_gateway_open_router(
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 6277a1749f..d418cb5668 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -5202,6 +5202,34 @@ where
pub type AuthenticationDataWithUserId = (AuthenticationData, Option<String>);
+/// Auth data paired with the dashboard user behind the request. Unlike
+/// `AuthenticationDataWithUserId`, it carries the whole token identity — a user holds different
+/// roles in different lineages, so the role backing *this* session has to be resolvable.
+#[cfg(feature = "v1")]
+pub type AuthenticationDataWithUser = (AuthenticationData, UserFromToken);
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> {
+ // Both halves are delegated rather than reimplemented, so the permission and tenant checks
+ // stay in one place and this cannot drift from them.
+ let (auth_data, auth_type): (AuthenticationData, AuthenticationType) =
+ self.authenticate_and_fetch(request_headers, state).await?;
+ let (user, _): (UserFromToken, AuthenticationType) =
+ self.authenticate_and_fetch(request_headers, state).await?;
+
+ Ok(((auth_data, user), auth_type))
+ }
+}
+
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithUserId, A> for JWTAuth
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b3defdee9a..86e2b81db9 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -287,6 +287,8 @@ pub enum Flow {
RoutingRetrieveDictionary,
/// Rule migration for decision-engine
DecisionEngineRuleMigration,
+ /// Migration status report for decision-engine
+ DecisionEngineMigrationStatus,
/// Routing update config
RoutingUpdateConfig,
/// Routing update default config